How to Use the Bash Functions
Introduction
Before we start talking on how to use the bash functions, let's briefly understand - What is a Bash Function?
Bash functions provide a way to group and reuse code, making scripts more modular and maintainable. They can be very helpful while writing your shell scripts.
A function is a set of commands that can be called multiple times. It makes the bash script more readable and helps in avoiding the repeated code.
In this tutorial, you will use Bash functions within your shell scripts. We will also address few FAQs related to the Bash function.
Defining Bash Functions
There are two ways in which a bash function can be declared:
The first format starts with the function name, along with parentheses. This is the preferable format:
function_name () {
commands
}
The single-line version:
function_name () { commands; }
The second format starts with the reserved word function
along with the function name:
function function_name {
commands
}
The single-line version:
function function_name { commands; }
Few points to keep in mind:
- The commands between the curly braces (
{}
) are known as the body of the function. The curly braces need to get separated from the body by spaces or newlines. - A function doesn't get executed by just defining it. You need to use the function name to invoke it. Commands will automatically get executed when a function is called in the shell script.
- The function should be defined before any calls to the function.
- While using single line “compacted” functions, add a semicolon
;
to last command in the function. - Keep the function names descriptive.
Below is an example:
#!/bin/bash
hello_world () {
echo 'hello, world'
}
hello_world
This is the analysis of the above code:
- In line -3, you are defining the function by its name. The curly-brace
{
marks the start of the function’s body. - The line -
4
is the function body. The function body can contain multiple commands, statements, and variable declarations. - Line -
5
, the closing curly bracket}
is there. It defines the end of thehello_world
function. - In line -
7
you are executing the function. You can execute the function as many times as you want. - After, running the script, it will print
hello, world
.
The Variables Scope
Global variables can be accessed from anywhere in the script. They don't depend on the scope. In bash, all variables are called global even if they are declared in the function.
Local variables are declared within the function body with the local
keyword and are useful only inside that function. Moreover, you can have local variables with similar names in different functions.
To have clarity on variables scope working in Bash. Look at the below 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"
The script will start by defining 2 global variables. The variables are both var1
and var2
. Then there is a function that sets a local variable var1
. Further, modifies the global variable var2
. After running the script, you will see the below output:
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, you can conclude that:
- When a local variable is set inside the function body with the same name as an existing global variable, it will have precedence over the global variable.
- The Global variables can be changed from within the function.
Returning the Values
Unlike functions in the real programming languages, the Bash functions do not allow the user to return a value when required. After its execution, it returns the value as the status of the last statement which is executed in the function. You will get 0
as status code for success and non-zero decimal number in the 1-255
range if it fails.
The return status is usually specified by using return
keyword. It is further assigned to a variable $?
. Here, the return
statement terminates the function. Think of it as the function’s exit status:
~/return_values.sh
#!/bin/bash
my_function () {
echo "some result"
return 55
}
my_function
echo $?
Output
some result
55
To return an arbitrary value from a function, you will need to use other methods as well. The simple option is assigning the result of the function to a global variable:
#!/bin/bash
my_function () {
func_result="some result"
}
my_function
echo $func_result
Output
some result
Another option is to return a value from a function is to send the value to stdout
. Do it using echo
or printf
like below:
#!/bin/bash
my_function () {
local func_result="some result"
echo "$func_result"
}
func_result="$(my_function)"
echo $func_result
Output
some result
Instead of just executing the function printing message to stdout, you are assigning the function output to func_result
variable. Do it using the $()
command substitution. The variable can be used later as per your need.
Passing Arguments to Bash Functions
To pass any number of arguments to the bash function, simply put them right after the function’s name. They should be separated by a space. It is a good practice to double-quote the arguments to avoid misparsing an argument with spaces in it.
- The passed parameters are
$1
,$2
,$3
…$n
. These are corresponding to the position of the parameter after the function’s name. - Also, the
$0
variable is reserved for the function’s name. - The
$#
variable holds the number of positional parameters/arguments passed to the function. - Both
$*
and$@
variables hold all positional parameters/arguments passed to the function. - When double-quoted, the
"$*"
expands to a single string. It is separated by space-"$1 $2 $n"
. - After double-quoting, here the
"$@"
expands to separate strings-"$1" "$2" "$n"
. - When not double-quoted, both
$*
and$@
are the same.
Below is an example:
#!/bin/bash
greeting () {
echo "Hello $1"
}
greeting "Joe"
Output
Hello Joe
FAQ's on how to use the bash functions
How do I define a bash function?
To define a bash function, use the following syntax:function_name() { commands; }
.
Can a bash function have parameters?
Yes, bash functions can have parameters. You can access these parameters within the function using the special variables $1
, $2
, and so on.
How do I call a bash function?
To call a bash function, simply use its name followed by parentheses: function_name
.
How do I pass arguments to a bash function?
Arguments can be passed to a bash function by listing them in the function call, separated by spaces: function_name arg1 arg2
.
Can I nest bash functions?
Yes, you can nest bash functions inside other functions. This allows for structuring complex scripts and reusing code.
Can I define bash functions in a separate file and include them in my script?
Yes, you can define bash functions in a separate file and include them in your script using the source
or .
command.
Can I use loops in a bash function?
Yes, you can use loop structures like for
, while
, and until
within a bash function to iterate over lists or perform repetitive tasks.
Conclusion
We hope this detailed guide helped you to use the Bash Functions.
If you have any queries, please leave a comment below, and we’ll be happy to respond to them for sure.