Shell script functions contain a set of instructions or commands that are being utilized again and again in shell script. They are utilized for when we are using a set of instructions again and again in our script. So instead of writing those commands again and again, we will create a bash script function & then we will use the name of the function instead of using those commands.
Functions are said to be MINI SCRIPTS INSIDE THE SCRIPT. We can use the way to create shell script functions,
function function_name {
commands or set of instructions
}
We can also use the programming language methods to create a shell script function,
function_name () {
Commands or set of instructions
}
Now let’s see an example for how we can create and use shell script functions in a bash script,
#!/bin/bash
function print{
echo “Welcome $USER, this is a fucntion”
}
var=1
while [ $var –le 5 ]
do
var=$[ $var + 1 ]
done
echo “Function is now complete”
In this script we created a function named “print” which is just printing a message to currently logged user, and then later in script we are using the same function inside a while loop.
We can also create variables that can only be used inside a function & will not work outside the function, these are called local variables. Local variables are created by mentioning ‘local’ before the variable, like
local var1=”this is a local variable”
Now let’s see an example for this as well,
#!/bin/bash
a=34
b=9
sum () {
local a=$1
local b=$2
echo $(( $a + $b ))
}
echo “a: $a and b: $b”
echo “Calling function sum with a: $a and b: $b”
sum 263 213
echo “a: $a and b: $b after calling function sum”
echo $(( $a + $b ))
Here we created a function named ‘sum’ & have asked it to take two values, which is later provided while calling the function. We are then printing the sum of both local as well as the normal variables. This is it for this tutorial on creating shell script functions.
Please do send us any queries you have or suggestions using the comment box below.