Monday, 5 August 2019

Linux - Simple View of Functions in Shell Script with some practical examples

Shell programming provides the feature of functions  just like any other programming  language. This help us develop the program in a modular manner.Using functions in 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?
  1. It helps us reuse the  code
  2. Improve readability
  3. Make debugging easier
  4. 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 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 <SID>”
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 <SID>”
echo “$PROG: Abort: exit status 1\n”
exit 1
fi
}

0 comments:

Post a Comment