Docs > Bash Handbook > Functions
Functions
In scripts we have the ability to define and call functions. As in any programming language, functions in bash are chunks of code, but there are differences.
In bash, functions are a sequence of commands grouped under a single name, that is the name of the function. Calling a function is the same as calling any other program, you just write the name and the function will be invoked.
We can declare our own function this way:
my_func () {
# statements
}
my_func # call my_func
We must declare functions before we can invoke them.
Functions can take on arguments and return a result — exit code. Arguments, within functions, are treated in the same manner as arguments given to the script in non-interactive mode — using positional parameters. A result code can be returned using the return
command.
Below is a function that takes a name and returns 0
, indicating successful execution.
# function with params
greeting () {
if [[ -n $1 ]]; then
echo "Hello, $1!"
else
echo "Hello, unknown!"
fi
return 0
}
greeting Denys # Hello, Denys!
greeting # Hello, unknown!
We already discussed exit codes. The return
command without any arguments returns the exit code of the last executed command. Above, return 0
will return a successful exit code. 0
.
Debugging
The shell gives us tools for debugging scripts. If we want to run a script in debug mode, we use a special option in our script's shebang:
#!/bin/bash options
These options are settings that change shell behavior. The following table is a list of options which might be useful to you:
Short | Name | Description |
---|---|---|
-f |
noglob | Disable filename expansion (globbing). |
-i |
interactive | Script runs in interactive mode. |
-n |
noexec | Read commands, but don't execute them (syntax check). |
pipefail | Make pipelines fail if any commands fail, not just if the final command fail. | |
-t |
— | Exit after first command. |
-v |
verbose | Print each command to stderr before executing it. |
-x |
xtrace | Print each command and its expanded arguments to stderr before executing it. |
For example, we have script with -x
option such as:
#!/bin/bash -x
for (( i = 0; i < 3; i++ )); do
echo $i
done
This will print the value of the variables to stdout
along with other useful information:
$ ./my_script
+ (( i = 0 ))
+ (( i < 3 ))
+ echo 0
0
+ (( i++ ))
+ (( i < 3 ))
+ echo 1
1
+ (( i++ ))
+ (( i < 3 ))
+ echo 2
2
+ (( i++ ))
+ (( i < 3 ))
Sometimes we need to debug a part of a script. In this case using the set
command is convenient. This command can enable and disable options. Options are turned on using -
and turned off using +
:
#!/bin/bash
echo "xtrace is turned off"
set -x
echo "xtrace is enabled"
set +x
echo "xtrace is turned off again"