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 () { 
So lets take an example of writing a basic function which will print something and save this file as and donot forget .sh extension.
printThis () { 
   echo "print from printThis function"
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
running above command will print "print from printThis function".

Now lets create one more function to do some computation


Function with Arguments

addNumbers() { 
   echo $result
addNumbers 25 24

As you can see when i run command bash 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 ./

Leave a Comment