Functions in Bash
A function which can also be referred to as subroutine or procedure is a block of code used for specific tasks. The function also has a property called re-usability. Bash script also provides functions.
Syntax:
funcationName(){ // scope of function } functionName //calling of function
#1. Bash – Create Function Example
Create your first function in shell script showing output “Hello World!”. Create a shell script “script.sh” using following code.
#!/bin/bash funHello(){ echo "Hello World!"; } # Call funHello from anywhere in the script like below funHello
Le’t execute script
$ ./script.sh Hello World!
#2. Bash – Function with Argument
The passing argument to functions is similar to pass an argument to command from shell. Functions receives arguments to $1,$2… etc. Create a shell script using following code.
#!/bin/bash funArguments(){ echo "First Argument: " $1 echo "Second Argument: " $2 echo "Third Argument: " $3 echo "Fourth Argument: " $4 } # Call funArguments from anywhere in the script using parameters like below funArguments 1 Welcome to TecAdmin
Let’s execute the script with the bash shell.
$ ./script.sh First Argument : 1 Second Argument : Welcome Third Argument : to Fourth Argument : TecAd,om
For more detailed uses of function in bash scripts visit here.