Linux bash functions

A Bash function is essentially a set of commands that can be called multiple times

4 min read
By myfreax
Linux bash functions
Linux bash functions

A Bash function is essentially a set of commands that can be called multiple times. The purpose of functions is to help you make bash scripts more readable and avoid writing repetitive code.

Compared to most programming languages, Bash functions are fairly limited. In this tutorial, we'll cover the basics of Bash functions and show you how to use them in shell scripts.

The syntax for declaring a bash function is very simple. They can be declared in two different formats. The first format starts with the function name, followed by parentheses. This is the preferred and more commonly used format.

function_name () {
  commands
}

One-line version:

function_name () { commands; }

The second format starts with a functionreserved word, followed by the function name.

function function_name {
  commands
}

One-line version:

function function_name { commands; }

{}The list of commands between curly braces is the body of the function. The curly braces surrounding the function body must be separated from the body by a space or newline.

Defining a function doesn't execute it. To call a bash function, just use the function name. Whenever a function is called in a shell script, the command of the function body is executed.

Functions must be defined before calling any functions. When using a single-line function, the semicolon ;must follow the last command in the function. You should always try to keep function names descriptive.

To understand this better, take a look at the following examples:

1 #!/bin/bash
2
3 hello_world () {
4   echo 'hello, world'
5 }
6
7 hello_world
~/hello_world.sh

On the line 3, we define the function by naming it, and use curly braces to {mark the beginning of the function body. Rows 4are function bodies. A function body can have multiple commands.

line 5, the closing curly brace }, defines hello_worldthe end of the function. At line 7we are executing the function. You can execute this function as many times as you want. If you run the script it will print hello, world.

variable scope

Global variables are variables that can be accessed from anywhere in the script, regardless of scope. In Bash, all variables are defined as global variables by default, even when declared inside a function.

Local variables can be declared within a function body using localkeywords and can only be used inside that function. You can use local variables of the same name in different functions.

To better illustrate how variable scoping works in Bash, let's consider an example:

#!/bin/bash

var1='A'
var2='B'

my_function () {
  local var1='C'
  var2='D'
  echo "Inside function: var1: $var1, var2: $var2"
}

echo "Before executing function: var1: $var1, var2: $var2"

my_function

echo "After executing function: var1: $var1, var2: $var2"
~/variables_scope.sh

The script first defines two global variables var1and var2. Then there is a function that sets local variables var1and modifies global variables var2.

If you run the script, you should see the following output:

Before executing function: var1: A, var2: B
Inside function: var1: C, var2: D
After executing function: var1: A, var2: D

From the above output, we can conclude. If you set a local variable with the same name as an existing global variable inside the function body, it will take precedence over the global variable. Global variables can be changed within a function.

return value

Unlike functions in real programming languages, Bash functions don't allow you to have a return value when called.

When a bash function completes, its return value is the status of the last statement executed in the function, 0indicating success and a non- 0decimal number in the range 1 - 255 indicating failure.

The return status can be specified using returnkeywords and assigned to global variables $?. returnstatement terminates the function. You can think of it as the exit status of a function.

To return any actual value from a function, we need to use other methods. The easiest option is to assign the result of the function to a global variable.

Another better option to get the return value from the function is to use echo or printfsend the value to standard output stdout.

#!/bin/bash

my_function () {
  echo "some result"
  return 55
}

my_function
echo $?
$? as return value
some result
55
#!/bin/bash

my_function () {
  local func_result="some result"
  echo "$func_result"
}

func_result="$(my_function)"
echo $func_result
Use echo as function return value
some result

Instead of simply printing the message to standard output, the function we execute uses a $()mechanism to assign to a variable func_result. Using this method func_resultvariable will hold the result of the function.

Bash function parameters

To pass any number of arguments to a bash function, just put them after the function name, separated by spaces. Best practice is to escape parameters with double quotes to avoid incorrectly using parameters with spaces.

Arguments can be passed through variables $1, $2, $3... $n, with the index 1...ncorresponding to the position of the argument after the function name.

$0The variable is reserved for the name of the function. $#Variables hold positional arguments or the number of arguments passed to the function. $*or $@variable holds all positional arguments or arguments passed to the function.

#!/bin/bash

greeting () {
  echo "Hello $1"
}

greeting "Joe"
~/passing_arguments.sh
Hello Joe

Conclusion

By now, you should have a good understanding of how to write bash functions. You might also want to learn how to use Bash functions to create memorized shortcut commands for longer commands .

If you have any questions or feedback, please feel free to leave a comment.