A Bash function is just a sequence of instructions that can be called several times. A function’s goal is to assist you make your bash scripts more understandable and to avoid repeating the same code over and over again. Bash functions are rather limited in comparison to most programming languages. In this article, we will go over the fundamentals of Bash functions and demonstrate how to use them in shell scripts in Linux.
Table of Contents
Prerequisites
- A Linux-powered computer.
- Terminal and Bash shell access.
- A text editor for writing bash scripts (Nano editor is used in the instructions).
Note: The Bash (Bourne Again SHell) is considered the default shell. If you have a different default shell, try adding the #!/bin/bash
shebang at the beginning of the scripts.
Create File and Make it Executable
You can create a file using touch
command.
touch ~/filename.sh
Now you can make the above file executable by issuing appropriate permissions.
chmod u+x ~/filename.sh
Now your file will be executable.
You can edit the file using the nano
command and add the bash
functions.
nano ~/filename.sh
Once you have added your functions, clickCTRL + X
followed by ENTER
to save and exit the file.
You can execute the file using the below command by just typing the filename.
~/filename.sh
Now you can start writing your Bash functions.
How to Use Bash Functions:
Inside a shell script: The function definition should come before any calls to the function within the script in this way. Define the function with the syntax function_name() and put the necessary commands within the curly brackets {}. Use the function’s name followed by parenthesis, such as function_name, to invoke it.
Directly in the terminal: Functions can also be defined at the terminal or in a bash configuration file like.bashrc or.bash_profile. To define the function, simply use the same syntax as in a shell script. Following its definition, the function can be invoked from the terminal as if it were a standard command.
Bash Function Syntax
There are two methods for declaring a bash function:
The most commonly used format is:
<function name> () {
<commands>
}
Alternatively, the same function can be written in a single line:
<function name> () { <commands>; }
Another option for writing a bash function is to use the reserved word function:
function <function name> {
<commands>
}
Alternatively, the same function can be written in a single line:
function <function name> { <commands>; }
When utilizing functions, keep the following behaviors and suggestions in mind:
- When writing commands in one line, they must end with a semicolon (;), whether in bash scripts or directly in the terminal.
- By including the function reserved word, parentheses are no longer required.
- The commands between the curly braces { } are referred to as the function’s body. The body can contain as many declarations, variables, loops, or conditional expressions as you want.
- When naming functions, try to use descriptive names. Although not required for testing functions and commands, descriptive names are useful in situations when other developers will be looking at the code.
Consider the following example to better understand this:
Create a file named hello_world.sh
and add the below bash
function to the file. Make it executable and execute the file.
Example
#!/bin/bash
hello_world () {
echo 'hello, world'
}
hello_world
The code defines a function called hello_world()
. The function prints the string hello, world
. The function is called on line 7, and the string is printed to the console.
Here is a more detailed explanation of the code:
- Line 3: The
def
keyword defines a function. The function name ishello_world
. The parentheses indicate that the function takes no arguments. - Line 4: The body of the function is indented. The
print()
statement prints the stringhello, world
to the console. - Line 5: The closing parenthesis marks the end of the function definition.
- Line 7: The
hello_world()
function is called. The function prints the stringhello, world
to the console.
Return Values
Bash functions, unlike functions in “real
” programming languages, do not allow you to return a value when called. When a bash function finishes, its return value is the status of the last statement run in the function, with 0 indicating success and a non-zero decimal number in the 1 – 255 range indicating failure.
The return status is provided using the return keyword and is given to the variable $?. The function is terminated using the return statement. Consider it to be the function’s exit status.
Create a new file named ~/return_values.sh
and paste the below bash
function.
Example
#!/bin/bash
my_function () {
echo "some result"
return 55
}
my_function
echo $?
output
some result
55
Another method
The simplest solution is to add the function’s output to a global variable:
#!/bin/bash
my_function () {
func_result="some result"
}
my_function
echo $func_result
output
some result
Variables Scope
Global
variables are variables that can be accessed regardless of scope from anywhere in the script. In Bash, all variables are defined as global by default, even if declared within a function. Local
variables can be declared within the function body using the local keyword and utilized just within that function. Local variables with the same name can exist in many functions.
Consider the following example to see how variables scope works in Bash:
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 begins with the definition of two global variables, var1 and var2. Then there is a method that sets a local variable var1 and updates a global variable var2.
When a local variable with the same name as an existing global variable is set within the function body, the local variable takes priority over the global variable. Changes to global variables can be made from within the function.
output
Before executing function: var1: A, var2: B
Inside function: var1: C, var2: D
After executing function: var1: A, var2: D
Bash Functions Arguments
To pass any number of arguments to the bash function, place them immediately after the function’s name, separated by a space. It is best to double-quote the arguments to avoid mispairing an argument with spaces in it.
Argument Description $0 The name of the function $1 The first argument passed to the function $2 The second argument passed to the function $3 \$ The third argument passed to the function \ \ … \ \ #
As an example, consider the following:
Create a new file named ~/passing_arguments.sh
and paste the below bash
function.
#!/bin/bash
greeting () {
echo "Hello $1"
}
greeting "cloudbooklet"
Hello cloudbooklet
Also read: You might also find useful our guide on How to Use Bash wait Command in Linux
Conclusion
In conclusion, bash functions are a powerful tool that can be used to improve the readability, maintainability, and reusability of your shell scripts. By following the steps outlined in this guide, you can easily create and use your own bash functions to automate tasks, reduce repetition, and make your scripts more efficient. Please feel free to share your thoughts and feedback in the comment section below.