Its pretty simple to work with functions of commandline bash/sh scripts.
Define function
This is how you define a function
func_name(){ <bash command_1> .... <bash command_n> }
eg:
say_hello(){ echo "Hello World" }
Calling the function
In order to call the function the function needs to be defined as above before you actually call it. Then you just use the name of the function
eg:
say_hello(){ echo "Hello World" } say_hello
Passing parameters to the function
Passing parameters to the function is pretty weird. Its the same as parameters being passed to a script. The function will have its own set of $* variable where the 1st parameter is $1, the next is $2 and so on.
eg:
say_hello(){ echo "Hello $1 $2" } say_hello "Saminda" "Wijeratne"
Defining variables inside a function
Defining variables inside function is same as how you’d do usually in a script. Only difference is that if you want the variable to be local to the function you need to use the keyword “local” when defining it.
eg:
say_hello(){ local first_name=$1 last_name=$2 #becomes a global variable echo "Hello $first_name $middle_name $last_name" } middle_name="Saminda" #global variable say_hello "Kushan" "Wijeratne" echo $firt_name echo $last_name
Passing a string as a variable is easy. But passing an array to a function is pretty tricky. Here’s an example on how to do it.
eg:
say_hello(){ eval "declare -A bio_data_array="${1#*=} #now bio_data_array is the array that was passed as a parameter echo "Hello ${bio_data_array['name']}" } declare -A bio_data bio_data["name"]="Saminda" bio_data["age"]=28 say_hello "$(declare -p bio_data)"
Returning values from the function
You’ll be surprised to know that bash functions never return anything. However you can capture what was printed by the function in the form of a string using the cool feature in bash where you can execute commands within “`” characters which the result is the output given by that command.
eg:
output_string=`say_hello $firt_name`
echo "This is what the say_hello function had to say: $output_string"
There are several other ways like using global variables or pass a variable name as a parameter to save the result of the function inside the function itself. But I prefer the above method since the function doesn’t have to worry about whether or not its a function or not.