Introduction
In this lab, we will learn about functions in shell programming. Functions are subroutines that implement a set of commands and operations. They are useful for performing repeated tasks.
In this lab, we will learn about functions in shell programming. Functions are subroutines that implement a set of commands and operations. They are useful for performing repeated tasks.
To create a function, use the function
keyword followed by the function name and curly brackets {}
. Inside the curly brackets, write the commands and operations that the function should perform.
function function_name {
command...
}
Functions can be called simply by writing their names. A function call is equivalent to a command. You can also pass parameters to functions by specifying them after the function name. The first parameter is referred to in the function as $1
, the second as $2
, and so on.
function function_B {
echo "Function B."
}
function function_A {
echo "$1"
}
function adder {
echo "$(($1 + $2))"
}
## FUNCTION CALLS
## Pass parameter to function A
function_A "Function A." ## Function A.
function_B ## Function B.
## Pass two parameters to function adder
adder 12 56 ## 68
Create a file called ~/project/functions.sh
and add the above code.
cd ~/project
chmod +x functions.sh
./functions.sh
Function A.
Function B.
68
In this exercise, we will create a function called ENGLISH_CALC
that can process sentences like '3 plus 5'
, '5 minus 1'
, or '4 times 6'
, and print the results as '3 + 5 = 8'
, '5 - 1 = 4'
, or '4 * 6 = 24'
respectively.
function ENGLISH_CALC {
a=$1
b=$3
signn=$2
if [ $signn == "plus" ]; then
echo "$a + $b = $(($a + $b))"
elif [ $signn == "minus" ]; then
echo "$a - $b = $(($a - $b))"
elif [ $signn == "times" ]; then
echo "$a * $b = $(($a * $b))"
fi
}
## Testing code
ENGLISH_CALC 3 plus 5
ENGLISH_CALC 5 minus 1
ENGLISH_CALC 4 times 6
Revise the file ~/project/functions.sh
to include the above code.
cd ~/project
chmod +x functions.sh
./functions.sh
3 + 5 = 8
5 - 1 = 4
4 * 6 = 24
Congratulations! In this lab, you have learned how to create and call functions in shell programming. Functions are useful for organizing code and performing repetitive tasks. You can now use functions to simplify your shell scripts and make them more efficient.