Table of Contents

Functions in Shell Scripting

In this article, we will be looking at using functions to improve the way we write shell scripts. Functions are a grouping of commands that can be reused based on its pre-defined name. The main benefit of using functions is that the code included in them can be reused easily. This is especially beneficial for code segments that are used regularly.

Let’s look at a simple example of shell scripting with the most popular line of code:

$ echo Hello World
Output:
Hello World

This example is quite straightforward. We use the echo command to print “Hello World” to the console.

Syntax of a Function

Let’s look at the two basic formats of function syntax:

# Defining the function

function function_name
{
	# included commands
}

function_name()
{
	# included commands
}

Like in many other programming languages, we can define a comment in shell scripting as well. Comments begin with a “#” (Hash or Pound sign) these are used to explain the behavior of the related lines of code.

The first line of each of these formats contains the function definition. This includes the name of the function. The rest of the function contains the commands to be executed within parentheses. This forms the basic structure of a function.

Let’s look at our previous example again, but this time, let’s convert it to a function.

# Defining the function

print_hello_world()
{
	echo Hello world
}

# Invoking the function

$ print_hello_world
Output:
Hello world

The first line contains the function definition as “print_hello_world()”. After that, the body of the function is defined with the echo command. After the closing parentheses of the function, we make a function call to the print_hello_world() function, and the resulting output is shown thereafter.

Characteristics of a Function

Let’s look at some advanced characteristics of functions that can be used to enhance the use of shell scripts.

Passing Parameters

Parameters can be passed in when calling a function. These are simply stated after the function call and not defined by type.

If you are familiar with other programming languages, you would know that these parameters need to be defined in the function definition, however with shell scripting, that is not the case. You simply refer to them within the function as follows:

# Defining the function

parameter_test()
{
 	echo "The following parameters were passed in: $@"
	echo “First parameter: $1” 
 	echo “First parameter: $2” 
}

# Invoking the function

parameter_test ABC XYZ
Output:
The following parameters were passed in: ABC XYZ
First parameter: ABC
Second parameter: XYZ

The output of this function has been defined to print out the parameters passed into it. The keyword “$@” refers to the full list of parameters passed in, while “$1” would refer to the first argument and so on.

If a function expects a certain number of parameters and a lesser number is passed, the missing parameters will simply be ignored. An error will not be thrown out as otherwise expected.

# Invoking the function

parameter_test DEF
Output:
The following parameters were passed in: DEF
First parameter: DEF
Second parameter:

Scope of Variables

If you are familiar with any other programming language(s), you would know the specifics regarding scope restrictions in that particular programming language. However, when it comes to shell scripting, there are no such restrictions, and all variables have a global scope. Let’s look at another example.

# Defining the function

scope_test()
{
 	echo "Scope Test function called with arguments: $@"
 	x=2
}

x=1
echo "x is $x"

# Invoking the function

scope_test 1 2 3
echo "x is $x"



Output:
x is 1
Scope Test function called with arguments: 1 2 3
x is 2

We begin the above example by defining the function “scope_test()”. This function prints out a sentence to the console with the parameters that are passed in.

We then change the value of the variable x to 1, print its value, execute our function, and finally print the value of x again. The output is self-explanatory and shows how the value of x can be set from anywhere in the script even though it was created within the function, making its scope global.

Returning values

Another useful characteristic of functions is returning a value after manipulating it or performing a calculation. The same can be done in shell scripting as well.

# Defining the function

return_test()
{
 	echo “Return Test invoked!”
 	return $1 
}

# Invoking the function

return_test 4

# Obtaining the value returned by the last command

ret_val=$?
echo "Return value after manipulation: $ret_val"
Output:
Return value after manipulation: 4

Decision Making and Loops

Decision making is an important part of programming and scripts. Shell scripts provide many flavors of IF / ELSE conditions, CASE statements, and loops. This is another article in itself. So let’s look at some of the most common examples.

# IF / ELSE statement

condition_test()
{
 	if [ "$1" -gt "1" ]; then
 		echo “Value entered is greater than 1!”
 	else
  		echo “Value entered is lesser than 1!”
 	fi
}

condition_test 3
condition_test 1

Output:
Value entered is greater than 1!
Value entered is lesser than 1!

This is an IF / ELSE condition, written in the flavor “if...else...fi statement” of shell scripting. The structure is similar to other programming languages other than for the fact that it doesn’t use parentheses. The “fi” keyword is used to mark the end of the conditional code.


# WHILE loop

loop_test()
{
	a=0

	while [ $a -lt 5 ]
 	do
 		echo $a
 		a=`expr $a + 1`
	done
}

loop_test


Output:
0
1
2
3
4

In this example, we define a basic while loop, with the condition a < 5. So the loop repeats itself 5 times and prints out the above output. Again, here too, this code differs from other programming languages in that it uses the keywords “do” and “done” to define the body.

Reusing Functions

Shell scripting provides two ways to easily reuse functions. The first is to add commonly used functions to the bash profile. The location of this file depends on the Operation System you use as well as how you are accessing the shell, especially on Windows.

The bash profile is loaded every time you log in to the shell. This is a good way to have easy access to commonly used functions.

Another way to reuse functions is to save them to a file. Open a shell script editor, such as vim or nano, and write in the function and commands that are required, and save the file with a .sh extension. You will now be able to execute these functions by typing the filename in the command prompt.

Conclusion

This article only scratches the surface of the use of functions in shell scripting. While there are some restrictions when compared to other programming languages, functions truly supplement the use of plain shell scripts in many ways. Some of these include reuse of code and segregation for clarity.

There is a lot more that can be done with functions, and we hope that we have sparked your curiosity to learn more. 

Related Topics:

python run bash command

Autocomplete Bash command line history

Related Posts