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.

  • Save the above code as
  • Make it executable by command “chmod +x”
  • Run using #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

  • Try to save above file as
  • Make it executable “chmod +x”
  • Run by “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


How to Read File word by word using bash shell script

Related Contents to follow