Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to declare shell functions in UNIX/Linux

Syed Muhammad Ali Mustafa

We use the function keyword to declare functions in UNIX/Linux, as shown below:

   //function body
  • _functionName_: name of the function.
  • function body: statements written within a function.

Call a function

To call a function, write its name where you want to call the function:


Add input parameters

To add input parameters to a function, write the parameters after the name of the function where it is called:

_functionName_ _param1_ _param2_

_param1_ and _param2_ are the input parameters.

Return value

To return a value from a function, use the return keyword followed by the return value.

Note: The function will not execute any statements written in the function after the return statement.

Example 1

Consider the code snippet below, which demonstrates the implementation of a simple function to print “Hello world!!” on screen.

printFunction () {
   echo "Hello world!!"

printFunction #calling the function

Example 2

Consider this example of a function that takes input parameters.

greetFunction () {
   echo "Hello $1!! How are you?"

greetFunction Ali #calling the function

Ali is the input parameter to the function greetFunction. $1 in line 2 is used to reference the value of the input parameter.

Example 3

Consider this example of a function that takes two numbers and returns their sum.

sumFunction () {
   return $(($1+$2))

sumFunction 2 5 #calling the function

sum=$? #getting return value of function

echo "2 + 5 = $sum"




Syed Muhammad Ali Mustafa
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring