Functions in Shell Script
If you are operating on a Linux OS, you will need to know about the purpose of shell script. This article with examples can help.
Join the DZone community and get the full member experience.
Join For Freethe best way to learn shell scripting is to fall in love with the command line. functions in shell script play an important role for re-usability.
what are functions in shell script all about?
a function is a group of commands that are assigned a name that acts like a handle to that group of commands. to execute this group of commands defined in the function, you simply call the function by the name you provided.
there will be cases where you need to execute a block of code that achieves a specific procedure several times in different places in your shell script. shell functions are like subroutines, procedures, and functions in other programming languages.
why functions in shell script?
• it helps us to reuse the code.
• improve the readability of the program.
• efficient use of variables inside the program.
• allows us to test the program part by part.
• displays program as a bunch of sub-steps.
syntax to use:
syntax1:
function function_name
{
###set of commands
}
syntax2:
function_name()
{
####set of commands
}
function is a key work that declares the function definition.
function_name is the name of the declared function.
curly braces {} acts as delimiters that enclose the function’s code.
set of commands are the code to be executed when the function is called.
so, a function is declared first, and then called when needed.
in the first syntax, you must use the keyword function, followed by your function name and open and close parentheses and curly braces to separate the contents of your functions to your main routine.
in the second syntax, consists of a function name, open and close parentheses and curly braces.
let’s have some shell script examples:
in this example, we are going to write a very small function that prints a line with “----”
let’s see how it works:
line 1: declares the function
print_line
.
lines 2 and 4: the curly braces
{ }
that delimit the function body.
line 3: the only statement in the function body: uses the echo command to print a line of “---' character.
line 5: calls the
print_line
function.
line 6: prints the provided argument
$1
.
line 7: calls the
print_line
function again.
note: “
$1
” in the above example will take the following values which you will give argument while executing the script.
1)
./function.sh “to automation laboratories”
prints “welcome to automation laboratories” (it will print the whole statement with the double quotes)
2)
./function.sh to automation laboratories
prints “welcome to” (it will print only “to” with the statement)
3)
./function.sh (without any argument)
prints “welcome” (it will print only welcome)
let’s have a look with one more example:
after creating the function myfunction, it was then invoked by calling its function name to our main routine. the main routine will be anywhere in our script that was not defined as part of our function.
#!/bin/bash
myfunction()
{
echo “oh! actually, it works”
}
myfunction
now let's rearrange our code to test whether functions can be declared anywhere in our script.
#! /bin/bash
echo “for testing”
myfunction
myfunction()
{
echo “oh! actually, it works”
}
the line 3 in the above snippet returns a command not found error. this only means that:
the function only works if it is declared before your main routine. the interpreter will return an error if you have declared your function after your main routine.
passing parameters on function
you can pass parameters and process those data in bash function. the code below shows the procedure on how to pass values in shell scripting:
#! /bin/bash
myfunction()
{
echo “first argument is as $1”
echo “second argument is as $2”
}
myfunction “hello” “world”
let’s understand the above:
-
we added the values "hello" and "world" after we called the
myfunction
. -
those values are passed to the myfunction as parameters and stored in a local variable.
-
the interpreter stores the passed values into predefined variables, which is named according to the sequence of passing the parameters, 1 as the starting name up to the order of passing.
-
notice that the "hello" word is stored to the variable 1 and value "world" is stored in variable 2.
note: the 1 and 2 in the above are local variables and thus, are not accessible to other parts of the script aside from the function where the parameters are being passed.
let’s recognize the above note point with below example:
#! /bin/bash
myfunction()
{
echo “first argument is as $1”
echo “second argument is as $2”
}
myfunction “hello” “world”
echo $1
echo $2
the
echo $1
and
echo $2
in the last two lines of our script have no display since the interpreter does not recognize both variables because they are both local to the myfunction.
let’s get into this more clearly by taking one more example:
we are going to write a function that estimates the length of a string. the string will be provided to the function as an argument. let’ see how this will look like.
hmmm…before that, why not we enhance some useful commands in the linux ?
"
wc -l
" : counts the number of lines
"
wc -w
" : counts the number of words
"
wc -m
" : count the number of characters
line 2: declares and initializes the variable length.
line 3: defines the function string_length.
lines 4 and 6: the function code block delimiters.
line 5: the only line of code inside the function:
length=`echo -n $1 | wc -m`
the argument passed to the function $1 is printed using the echo command with the option
–n
that prevents echo from inserting newline character at the end.
the output of the command echo
–n $1
is piped into the input stream of the command
wc –m
(which counts the characters in its input).
the result of the above composite statement echo -n $1 | wc -m is assigned (by using backticks ‘ ‘) to the variable length.
line 7: reads an input string from the user, and assigns it to the variable
str
.
line 8: calls the
string_length
function and passes the variable
str
to it. the result of calling the function is estimating the length of str and storing the calculated length in the variable length.
line 9: prints the result to the user.
bash function return
bash function can pass the values of a function's local variable to the main routine by using the keyword return. the returned values are then stored to the default variable $? let’s take an example:
we pass the parameters int1 and int2 to the add function. next, the
add
function processes it through the line
sum=$(($1+$2))
. then the value of the sum variable is passed to the main routine through the line
return $sum
. by default, the values of
$sum
will be stored to the default variable
$
? finally, the line echo
"the result is: " $?
prints the result.
note: shell scripts can only return a single value.
recursive function means within a function definition, and inside the function’s code, a call statement can appear calling the function (being defined) itself. this should be controlled by a test condition, to assure the function will converge. if no condition specified, or the wrong one is used, the function will keep calling itself forever.
now enhance this recursive function with a factorial example:
result=1
: this line initializes the variable result to 1.
factorial_function
: declares the factorial function.
the function body staring delimiter {
if [ $1 -gt1 ]; thenchecks whether the argument provided to the function is greater than 1.
if so, the following two lines are executed:
-
let “result *= $1”
: this multiplies the current value of result by the argument passed to the function. -
factorial $(($1-1))
: this calls the factorial function recursively, and passes to it $1-1 as an argument.
the function body closing delimiter }
after the function has been declared, this is again the main script code:
factorial $1
the main script calls the factorial function and passes to it the command line argument passed to the script $1. don’t confuse the $1 that represents the first command-line argument, and the $1 that represents the first argument passed to a function.
the last line prints the result to the user.
1. first, the result variable is set to 1.
2. the interpreter encounters the function definition.
3. the function is called with an argument 4. the control is transferred to the function that works as follows:
a) the argument (which is now 4) is checked if it is greater than 1 (which is case). if so, the following two lines are executed:
i) the usual accumulative multiplication operation is done: result is multiplied by the argument $1, and the result is stored in the variable result.
ii) the factorial function is called “recursively” and passed 3 as an argument. the control is transferred again to factorial function whose argument now is 3.
b) the argument “3” is checked if it is greater than 1 (which is case). if so, the above two steps (i and ii) are executed. the step ii again calls the factorial function with 2 as an argument.
c) this continues until the factorial function is called with argument 1. at this time, the if condition fails, and the function is terminated.
4. the control is back to the main script, and the first line after the function call is executed (which is the echo command that prints the result to the user).
we have talked about functions in linux shell scripts. a function is a block of code that achieves a specific task. functions can take argument(s) or called without arguments at all. we have illustrated our talk with examples.
i hope you find this post useful.
please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.?
Opinions expressed by DZone contributors are their own.
Comments