Functions in Bash Scripting are a great way to reuse code. In this section you'll learn how they work and what you can do with them.
Think of a function as a small script within a script. It's a small chunk of code which you may call multiple times within your script. They are particularly useful if you have certain tasks which need to be performed several times. Instead of writing out the same code over and over you may write it once in a function then call that function every time.
Creating a function is fairly easy. They may be written in two different formats:
function_name ()
{}
or
function function_name
{
}
The function can be called with just function_name
Example1:
f()
{
echo “This is a
test function...f”
}
f
Example2:
function f
{
echo “This is a
test function...f”
}
f
Passing Arguments
It is often the case that we would like the function to process some data for us. We may send data to the function in a similar way to passing command line arguments to a script. We supply the arguments directly after the function name. Within the function they are accessible as $1, $2, etc.
Example:
f()
{
echo "first
argument is=$1"
echo "second
argument is= $2"
}
f first second #
function call with arguments
Return Values
Most other programming languages have the concept of a return value for functions, a means for the function to send data back to the original calling location. Bash functions don't allow us to do this. They do however allow us to set a return status. Similar to how a program or command exits with an exit status which indicates whether it succeeded or not. We use the keyword return to indicate a return status.
Typically a return status of 0 indicates that everything went successfully. A non zero value indicates an error occurred.
We can use command substitution to return some value.
Example:
lines_in_file () {
cat $1 | wc -l
}
num_lines=$( lines_in_file file )
echo The file has $num_lines lines in it.Variable scope
Scope refers to which parts of a script can see which variables. By default a variable is global. This means that it is visible everywhere in the script. We may also create a variable as a local variable. When we create a local variable within a function, it is only visible within that function. To do that we use the keyword local in front of the variable the first time we set it's value.
local var_name=value
It is generally considered good practice to use local variables within functions so as to keep everything within the function contained. This way variables are safer from being inadvertently modified by another part of the script which happens to have a variable with the same name (or vice versa).
Example:
var_change () {
local var1='local 1'
echo Inside function: var1 is $var1 : var2 is $var2
var1='changed again'
var2='2 changed again'
}
var1='global 1'
var2='global 2'
echo Before function call: var1 is $var1 : var2 is $var2
var_change
echo After function call: var1 is $var1 : var2 is $var2
Comments
Post a Comment