Shell programming provides the feature of functions just like any other programming language. This helps us develop the program in a modular manner. Using functions in a shell script to perform repetitive tasks is an excellent way to create code reuse. Code reuse is an important part of modern object-oriented programming principles.
What are functions in Shell Script?
Functions are group pieces of code in a more logical way or practice the divine art of recursion.
Why do require functions?
- It helps us reuse the code
- Improve readability
- Make debugging easier
- Display program as a bunch of steps
How to declare the function ?
Declaring a function is just a matter of writing function
exampl_func () { Code.. }
How to call the functions in shell script?
Calling a function is just like calling another program, you just write its name.
exampl_func
Different type of Functions in shell script
Function with out parameter
!/bin/ksh Hello () { Echo “hello how are you” } hello exit 0
Function with parameter passing
Count and display the number of files in the specified directory.
!/bin/ksh
FILECOUNT ()
{
CDIR=$1
Fcount=ls -l $CDIR | wc –l
printf "There are $Fcount files in $CDIR. \n"
}
FCOUNT /export/home/
exit 0
Function with a return parameter
!/bin/sh Define your function here Hello () { echo "How are you $1 $2" return “success” } Invoke your function Hello Tom Hanks #Capture value returned by last command ret=$?
Some useful examples of functions in shell script
Setting the Oracle environment
set_Ora_Env () { ORAENV_ASK=NO; export ORAENV_ASK export ORACLE_SID=$1 . /usr/local/bin/oraenv }
Checking the OS username
Check_OS_Username ()
{
USER=id|awk -F'(' '{print $2}'|awk -F')' '{print $1}'
case ${USER} in
$1)
: ;;
*)
echo
echo "$PROG: Must be run as user $1"
echo "Usage: $PROG "
exit 1;;
esac
}
Checking the number of arguments passed in the scripts
Check_Options () { if [ $# -ne 1 ] then echo "\n$PROG: Incorrect number of arguments" echo "Usage: $PROG " echo "$PROG: Abort: exit status 1\n" exit 1 fi } Related articles in Shell scripting What is shell and Shell Scripts If statement in Shell Scripts loop in shell scripts awk command in Unix Unix shell function examples