Bash Function Tutorial

Bash is a command-line interface for the Linux and Unix operating systems where also provides some programming features like functions. The purpose of the bash function is to execute single or multiple commands again and again just calling the function not all commands. Also, the programming languages provide functions but they are more advanced than bash functions. But the bash functions provide very useful features for the system administrators and DevOps.

Define Bash Function

Bash functions can be created in different ways. The most readable way is using the function keyword before the definition of the function. The syntax of the bash function definition is like below.

function FUNCTION_NAME {
   BODY
}
  • function is the keyword used to specify a function definition.
  • FUNCTION_NAME is the name of the function.
  • BODY is the function body where commands are executed when the function is called.

In the following example, we create a bash function named hello_world which simply prints “hello world” to the bash.

function hello_world {
   echo "Hello World"
}

Call Bash Function

The easiest part of the Bash function is calling it. The bash function can be called in the command line interfaces or terminals just using the function name.

#!/bin/bash


function hello_world {
   echo "Hello World"
}

hello_world

Bash Function Variables or Parameters

Some bash functions may require to accept parameters for different cases. Parameters or variables are useful to specify different values. The function parameters are assigned into $1 , $2 , $3 etc. according to their row. In the following example, we provide two parameters to the hello_world function.

#!/bin/bash


function hello_world {
   echo "Hello " $1 $2
}

hello_world "İsmail" "Baydan"

Bash Function Return Value

Bash functions are executed to accomplish some tasks where sometimes some values can be returned. We can use the return keyword in order to return value after the function execution. The returned value can be get by using the $? .

#!/bin/bash


function hello_world{
   return "Hello Wordl"
}

hello_world

echo $?

Leave a Comment