
Bash functions are reusable blocks of commands that enhance script readability and prevent task duplication by allowing other elements to reference them. A function in Bash allows you to group commands that perform a specific task. You can call and execute functions by referencing their names in any part of a script or a Bash shell environment.
This article explains how to use functions in Bash to efficiently write reusable commands in scripts.
You can define a function in Bash using two formats depending on your scripting style. You can use the function name and parenthesis () or the function keyword followed by a function name as detailed below.
Bash function syntax with parenthesis ().
Inline parenthesis format:
Bash function syntax with the function keyword.
Inline function format:
You can create a function in a Bash shell environment or a script and reuse it by calling its name. Follow the steps below to create Bash functions using the parenthesis and function keyword methods.
Create a new inline greet function using the parenthesis method in a shell environment.
Output:
Create an inline greet function using the function keyword method.
Output:
Create a new greet.sh script.
Add the following contents to the greet.sh file.
Save and close the file.
In the above script, the greet function outputs the Hello World! This is a function message using the echo command when the script calls the greet function.
Run the script using Bash.
Output:
Calling functions invokes the commands or code within them. You can call a function in Bash using its name and include optional arguments to invoke specific commands within the function. You can pass the following arguments when calling functions in Bash:
$0: References the function name.$1, $2, etc: Refers to positional function parameters.${!variable}: Accesses the value of variable with indirect referencing.$#: Stores the number of positional parameters to pass to a function.$*: Expands all positional parameters into a single string separated by spaces.$@: Expands positional parameters as separate quoted strings.Follow the steps below to create, call, and pass function arguments to invoke specific commands.
Create a new call-functions.sh script.
Add the following contents to the call-functions.sh file.
Save and close the file.
In the above script, the greeting function imports the greet variable value and outputs it using the echo command when the script calls the function.
Run the script using Bash.
Output:
Create another call-function-args.sh script.
Add the following contents to the call-function-args.sh file.
Save and close the file.
In the above code, the script calls the calculate function using the $1 and $2 arguments to forward the input result as values to the local a and b variables. The sum variable stores the sum of the a and b variables while the echo command outputs the final result.
Run the script using Bash.
Output:
Unlike other programming languages, Bash functions do not return status codes automatically. A function returns the status of the last command by default, 0 for success, or a non-zero number between 1 to 255 for failure. Follow the steps below to use the return statement to terminate a function and display a specific custom status codes.
Create a new return-function.sh script.
Add the following contents to the return-function.sh file.
Save and close the file.
In the above code, the script calls the greetings function to output a Hello World message, passes the status code to the $? variable, and returns a non-zero 200 status code.
Run the script using Bash.
Output:
The exit command terminates an entire function and returns the exit status code. exit is similar to return and allows exiting a function in case of any errors or unmet conditions to stop all additional executions. Follow the steps below to use the exit command to return the exit status in a function.
Create a new exit-function.sh script.
Add the following contents to the exit-function.sh file.
Save and close the file.
In the above script, the exit command terminates the function from executing any further tasks and returns a non-zero exit code of 2.
Run the script using Bash.
Output:
Variables in Bash store specific data that you can use with functions to hold repeated values or manipulate data. Functions support global and local variables:
local keyword and are only accessible inside the function.Follow the steps below to create and reference variables in functions.
Create a new var-function.sh script.
Add the following contents to the var-function.sh file.
Save and close the file.
In the above script, the greetings function uses a local name variable and imports the global variable greeting. The function inputs user data from the username variable using the read command value as an argument. The echo command combines the variables into a single result and displays a message when the script calls the function.
Run the script using Bash.
Enter a name such as John Doe when prompted to test the function in Bash.
You can use Bash functions with loops to continuously execute commands or tasks over several times. Bash functions work with for, while, and until loops to execute repetitive tasks within or outside a function. Follow the steps below to use loops within and outside a Bash function to execute repeated tasks.
Create a new loop-in-function.sh script to use internal loops.
Add the following contents to the loop-in-function.sh file.
Save and close the file.
In the above script, the count function uses a for loop to continuously increment the value of the var variable and print its current value if it's less than the input argument value of 10 stored in the compare local variable.
Run the script using Bash.
Output:
Create another loop-out-functions.sh script to use external loops.
Add the following contents to the loop-out-functions.sh file.
Save and close the file.
In the above script, the greetings function imports the username variable from the input argument when the external for loop calls the function. The for loop continuously sets a new username value from the names array.
Run the script using Bash.
Output:
Bash Functions use conditional statements to execute specific commands or tasks when a condition evaluates to true. You can use conditional statements such as if, elif, if-then, and case inside or outside functions to execute specific commands. Follow the steps below to use conditional statements with functions in Bash.
Create a new if-elif-in-function.sh script.
Add the following contents to the if-elif-in-function.sh file.
Save and close the file.
In the above script, the count function imports an argument from the user input using the read command when the script calls the function and assigns it to the local var variable . The if-elif conditional statement evaluates if the var value is greater or less than zero to output a message using the echo command.
Run the script using Bash.
Enter a value such as 1 and verify the script's output:
Create a new case-out-function.sh script.
Add the following contents to the case-out-function.sh file.
Save and close the file.
In the above code, the script calls the help_page function in a case conditional statement when the user input fails to match any pattern to display the help information page.
Run the script using Bash.
Enter help when prompted to match the function's pattern to display the help page.
Output:
You have used functions in Bash to create reusable commands and run tasks. You can use functions with arrays, loops, expressions, and other elements in Bash to enable code reusability. In addition, you can use functions in Bash to automate scripts or run system administration tasks that require reusable commands.
0 Comments
Be the first to comment and share your perspective with the community.