Functions In Shell Script

Functions In Shell Script

Functions are group of statements to perform specific task. Functions are used for break down larger applications into different smaller components. Here we will take examples of two functions with argument and without arguments.

Function without Arguments

Function have return statements which returns something after execution of code block. Those function which returns something after execution are calledfruitful functions. Here is example writing basic function in shell script without arguments.

functionName () { 
   commands_list
}
So lets take an example of writing a basic function which will print something and save this file as printthis.sh and donot forget .sh extension.
#!/bin/bash
printThis () { 
   echo "print from printThis function"
}
printThis
First line in above code is shebang which will include essentials linux files, second line start with function name printThis and i have used simple echo statement to print data on terminal, to execute that script you can use
[email protected]:~# bash printthis.sh
running above command will print "print from printThis function".

Now lets create one more function to do some computation

PrintThis

Function with Arguments

#!/bin/bash
addNumbers() { 
   a=$1
   b=$2
   result=$(($a+$b))
   echo $result
}
addNumbers 25 24
PrintThisOutput

As you can see when i run command bash printthis.sh it produced sum of two numbers. One more way to run this command is to change mode mode script using chmod command and then run script as ./printthis.sh.

Leave a Comment