Linux Shell Scripting – Functions

How do I create a shell script function using Bash under UNIX / Linux operating systems?

Functions are nothing but small subroutines or subscripts within a Bash shell script. You need to use to break up a complex script into separate tasks. This improves overall script readability and ease of use. However, shell function cannot return value. They return a status code.

All functions must be declared before they can be used.

function welcome(){
  Commands
}

OR

 
welcome(){
 Commands
 return $TRUE
}

You can call function by typing its name:

 
welcome


eg:

cat > hello.sh
#!
welcome(){
echo "Welcome to Linux Shell Scripting !!" 
}
welcome   # calling the function
echo ""   # a free lne
welcome   # calling the function

the output of the above should be

# sh hello.sh
Welcome to Linux Shell Scripting !!

Welcome to Linux Shell Scripting !! 

by using this we can avoid repeating the codes like other programming languages.

Facebook Comments