Functions in bash/sh scripts

Its pretty simple to work with functions of commandline bash/sh scripts.

Define function

This is how you define a function
  <bash command_1>     
  <bash command_n>
  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
  echo "Hello World"


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.
  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.
  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.
 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
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.
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.

Tags: , , , , , , , ,

One Response to “Functions in bash/sh scripts”

  1. Bash working with the filename « Saminda Wijeratne’s Weblog Says:

    […] Saminda Wijeratne’s Weblog Just another weblog « Functions in bash/sh scripts […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: