Subprograms/Subfunctions
Purpose
create reusable blocks of bash commands
Syntax
function_name () {
commands.... ;
return ;
}
prompt> print_something () {
echo Hello you typed $1 ;
return 1 ;
}
prompt> print_something frog
Hello you typed frog
prompt> print_something toad
Hello you typed toad
EXERCISE:
Create a script that recursively uses a subfunction to calculate factorials but stops if you enter 0.
prompt> vi factorial.sh
#!/bin/sh
factorial()
{
if (( "$1" > "1" )) ; then
i=$(( $1 - 1 ));
j=$(factorial $i )
k=$(($1 * $j))
echo $k
else
echo 1
fi
}
while :
do
echo "Enter a number:"
read x
if (( $x == 0 )); then break ; fi;
factorial $x
done
prompt> ./factorial.sh
Enter a number:
5
120
Enter a number:
4
24
Enter a number:
0
prompt>
Prev CASE STATEMENTS | Next BASH scripting | UP : BASH scripting | Top : Course Overview © 2017 Texas Advanced Computing Center