Functions in shell Script


Last Blog Review →
In the last blog we understood, the use of case statements to use instead of using multiple if else statements along with its syntax and shell scripts.
1. What are functions in shell script ?
In shell script always the execution of code starts from top to bottom. So, when using the function in shell script always write the Function Def first then Main Function. If the Main Function is written before the Function Definition then error is generated as the shell script will not understand the Main Function without the Function Definition is encountered. And don't use exit statement instead use return statement in Function. The return statement doesn't return any value as in C/Java, the return statement is similar to the exit statement so it can only return a number and not a text.
2. Syntax
function launch () { ----Function Definition---
..
..
} ----Function Definition---
launch parameters ----Main Function----
3. Function without return and with return
a. without return statement
function add () {
result $(( $1 + $2 ))
echo $result
}
sum=$( add 3 5 )
b. with return statement
function add () {
return echo $(( $1 + $2 ))
}
add 3 5
sum=$?
4. Lets improve the calculator program using functions.
.:~$ vim /home/bob/calculator.sh
:~$ cat /home/bob/calculator.sh
#!/bin/bash
function read_numbers(){
read -p "Enter Number1: " number1
read -p "Enter Number2: " number2
}
while true
do
echo "1. Add"
echo "2. Subtract"
echo "3. Multiply"
echo "4. Divide"
echo "5. Quit"
read -p "Enter your choice: " choice
case $choice in
1) read_numbers
echo $(( $number1 + $number2 )) ;;
2)
read_numbers
echo $(( $number1 - $number2 )) ;;
3)
read_numbers
echo $(( $number1 * $number2 )) ;;
4)
read_numbers
echo $(( $number1 / $number2 )) ;;
5) break
esac
done
.:~$ chmod 700 calculator.sh
.:~$ ./calculator.sh
1. Add
2. Subtract
3. Multiply
4. Divide
5. Quit
Enter your choice: 1
Enter Number1: 5
Enter Number2: 2
7
1. Add
2. Subtract
3. Multiply
4. Divide
5. Quit
Enter your choice: 5
.:~$
Conclusion
In the this blog we understood, what are functions in shell script. The syntax of the functions and the use of the return statement in the functions. And we saw the example using function that improved the cal. script.
Subscribe to my newsletter
Read articles from Mihir Suratwala directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Mihir Suratwala
Mihir Suratwala
Hi, How are you !! Hope you doing good.... I got introduced to Cloud initially. As I went ahead learning what is cloud and how it works, then got to know a field which is DevOps that makes Cloud model more effective. So, as I started working & got good experience on AWS. I have been learning the DevOps tool and technologies on how to use it with the Cloud, which will give me good understanding on how Cloud and DevOps go hand in hand to deploy my applications.