Functions

Functions provide a method of grouping frequently used (sets of) commands together using an easily referenced user defined name. This allows pieces of code to be grouped in a more logical way, that can be called upon or repeated, as required.

 

Created by placing parentheses after the function name, or by use of the function keyword followed by the function name:

 

function_name () {

<commands>

}

or

function function_name {

<commands>

}

 

Either of the above is valid, but unlike other programming languages the parentheses can not be used to pass arguments into the function.

 

To use a function, simply specifying the function name:

#! /bin/bash

myFunc () {
	echo "Hello, World!"
}

myFunc

 

Arguments can be passed into a function in a similar method as passing in from the command line:

#! /bin/bash

myFunc () {
	echo "Hello, $1"
}

myFunc World!

 

Numerical values can be returned from the function by using the keyword return and then specifying the numerical value to be returned, which can then be accessed via use of the special variable $?

#! /bin/bash

myFunc () {
	echo "Hello, $1"
	return "17"
}

myFunc World!

echo "myFunc returned $?"

*Typically a return status of 0 indicates that everything went successfully. A non zero value indicates an error occurred.

 

Command substitution can be used to return the result of a calculation:

#! /bin/bash

fileLines () {
	cat $1 | wc -l
}
numLines=$( fileLines $1 )

echo The file $1 has $numLines lines in it.

The target file is passed in as an argument when running the script:

  • myScript.sh targetFile.txt

The result is that the passed in file is used as the argument when the function is called and its returned value is assigned to the calling variable, ultimately counting and echoing the number of lines in the file.