3.4 Functions

Authored by Atri

In the event you have a series of command statements you would like to easily repeat, Bash supports the ability to write these statements inside a function.

example() {
	echo "Hello world!"
}

example

When you run this function, it will execute the statements provided sequentially, allowing for the ability to write either simple macros or even complex logic trees with branching statements using 2.5 Conditionals.

Function Arguments

In Bash, functions also provide us with the ability to retrieve command-local variables using the same numeric syntax we use to retrieve shell arguments.

example() {
	echo $1
	echo "Hello $2"
	echo $3
}

example 1 2 3

If you would like, it also supports $@ arguments to retrieve the full argument collection.

example() {
	echo $@
}

example This is a multi argument statement which will be echoed together!

While these examples are very simple, functions enable us to write scalable and maintainable logic. Many complex scripts will rely on these to help us describe exactly what a program is trying to accomplish. But what about variables? How does Bash handle those, seeing as variables in bash are typically defined globally?

Local Variable Declarations

Like all major programming languages, Bash does still provide us a way to define locally-scoped variables via the use of the local keyword. Invoking this within a function call will scope its declaration to the body of the function, rendering it inaccessible from outside.

example() {
	local hello="Hello world!"
	echo $hello
}
# Run the command
example
# This will return nothing as this is not defined.
echo $hello
Tip

Its advisable to make sure to properly understand the boundary or scope of your functions. The key to writing clean code is specifically in its ability to simplify actions into regular groups of statements. If you shove too much into a single function, this will defeat the intended purpose of the construct.