bash function definition syntax
In Bash, a function is a tool used to encapsulate a series of commands. Functions can accept input parameters and return output values; they can be used within scripts or called directly from the command line.
The syntax for defining a function is as follows:
function_name () {
commands
}
In this syntax, function_name represents the name of the function, while commands refers to the series of commands that need to be executed. Functions can accept parameters, which are referenced using variables such as $1, $2, $3, and so on.
For example, the following is a simple function that adds two passed arguments and returns the result:
add () {
sum=$(expr $1 + $2)
echo $sum
}
When invoking this function, parameters can be passed as shown below:
result=$(add 2 3)
echo $result # Output: 5
In the example above, we defined a function named add that accepts two parameters and adds them together. The return value of the function is output via the echo command. We then call the function, assign its return value to the variable result, and finally output the value of this variable.
In addition to defining functions using the function_name method described above, another way can be used:
function function_name {
commands
}
These two methods are equivalent; you may choose whichever one you prefer based on personal preference.