Functions in shell script

Functions in shell script:

Contents

The best way to learn shell scripting is to fall in love with the command line.Functions in shell script plays an important role for re-usability.

Function

 

What 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 get have function in shell script examples:

In this example, we are going to write a very small function that prints a line with “—-”
1) function print_line
2) {
3)echo ” —————————————————”
4) }
5) print_line
6) echo ” Welcome $1″
7) print_line

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 giveas 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”

Function5

 

Let’s understand the above:

1) We added the values “Hello” and “World” after we called the myfunction.
2) Those values are passed to the myfunction as parameters and stored in a local variable.
3)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. 4) 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
1)#! /bin/bash
2) length=0
3) string_length()
4) {
5) length=`echo -n $1 | wc -m`
6) }
7) read -p “Enter the string :” STR
8) string_length $STR
9) echo -e “\nYou entered $length Characters”

function6

 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: #!/bin/bash add() { sum=$(($1+$2)) return $sum } read -p “Enter the first integer: ” int1 read -p “Enter thesecond integer: ” int2 add $int1 $int2 echo “The result is: ” $?

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 Calls

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 factorial example:

function8

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.?







Divya Gupta - Automation Laboratories

Linux System Admin | shell scripting | Ansible developer

Leave a Reply

Your email address will not be published. Required fields are marked *