In this blog we will learn How to write function in shell script. Functions in any language or script is a subroutine.  Writing functions in shell script means is a way to manage large shell scripts. Let us see a simple example.

#!/usr/bin/bash

HelloWorld()
{
  a=5;
  b=6;
  c=$((a + b))
  echo "$a + $b is $c"
}
#call function HelloWorld()
HelloWorld
  • Save the above code as HelloWorld.sh
  • Make it executable by command “chmod +x HelloWorld.sh”
  • Run using #sh HelloWorld.sh , after ruuning the command we will see output as

5 + 6 is 11

Returning value from Shell functions

Shell functions do not return value. We can use a simple trick to make shell functions to return a value. Let us see below example.

How to write function in shell script

#!/usr/bin/bash

HelloWorld()
{
  a=5;
  b=6;
  c=$((a + b))
  echo $c #echo value of c
}

#call function HelloWorld()
v=$(HelloWorld)
echo $v
  • Try to save above file as add.sh
  • Make it executable “chmod +x add.sh”
  • Run by “sh add.sh” command from Linux/Unix terminal.
  • The output would be 11

How it works

  • In our function HelloWorld(), at the end we have echoed value of shell variable c.
  • Look at the calling method of HelloWorld() function, v=$(HelloWorld). this statement call the shell function and echo value of  variable c would be assigned to variable v.
  • We have just printed saved value of v by echo $v

Ref:

How to Read File word by word using bash shell script

https://www.shellscript.sh/functions.html



Related Contents to follow