Open In App

Shell Scripting – Functions and it’s types

Last Updated : 12 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Shell scripting is a powerful tool used to automate tasks in Unix-like operating systems. A shell serves as a command-line interpreter, and shell scripts often perform file manipulation, program execution, and text output. Here, we’ll look into functions in shell scripting, exploring their structure, usage, and types to help you effectively incorporate them into your scripts.

What is a Function in Shell Scripting?

A function is a collection of statements that execute a specified task. Its main goal is to break down a complicated procedure into simpler subroutines that can subsequently be used to accomplish the more complex routine. For the following reasons, functions are popular:

  • Code Reusability: Functions allow you to write code once and use it multiple times throughout your script.
  • Enhanced Readability: Functions help organize code into logical blocks, making scripts easier to read and understand.
  • Modularity: Functions enable modular programming, where different tasks are handled by separate, self-contained functions.
  • Ease of Maintenance: Functions simplify debugging and updating code since changes can be made in one place rather than throughout the script.

Basic Structure of a Function in Shell Scripting

The basic syntax for defining a function in shell scripting is:

function_name(){
    // body of the function
}
  • The function_name can be any valid string and the body can be any sequence of valid statements in the scripting language.
  • The body of the function can include any sequence of valid shell commands or statements.

Example

Let us try to understand the concept of functions by looking at an example. The following is a code to print all the prime numbers between a range [le,ri].

It consists of a function ‘is_prime()‘ which is used to check if the given number is a prime or not. In this function, we use the variable ‘$1’ to access the first argument, which is the number itself. In scripting languages, we can access arguments by ‘$i’, where ‘i’ is a number that signifies the position of the argument.

echo -n "Enter Left-End: " 
read le
echo -n "Enter Right-End: " 
read ri

is_prime(){ 
   if [ $1 -lt 2 ]; then 
       return 
   fi 
   ctr=0 
   for((i=2;i<$1;i++)){ 
       if [ $(( $1 % i )) -eq 0 ]; then 
           ctr=$(( ctr +1 )) 
       fi 
   }
   if [ $ctr -eq 0 ]; then 
       printf "%d " "$1" 
   fi 
}
printf "Prime Numbers between %d and %d are: " "$le" "$ri"
for((i=le;i<=ri;i++)){ 
   is_prime $i 
} 
printf "\n" 

 

Types of Functions

The functions in shell scripting can be boxed into a number of categories. The following are some of them:

1. The functions that return a value to the caller.

The return keyword is used by the functions for this purpose. The following is one such function used to calculate the average of the given numbers.

find_avg(){ 
  len=$#
  sum=0
  for x in "$@"
  do
     sum=$((sum + x))
  done
  avg=$((sum/len))
  return $avg
}
find_avg 30 40 50 60
printf "%f" "$?"
printf "\n"

Output:

 

Explanation:

  • The function ‘find_avg()’ calculates the average of the given numbers and returns it using the ‘return’ statement.
  • Since the ‘return’ value is restricted to integers between 0 and 255, it prints the result using ‘$?’, which holds the exit status of the last executed command.

2. The functions that terminate the shell using the ‘exit’ keyword.

These functions use the ‘exit’ command to stop the shell entirely. This can be useful for error handling or when a certain condition requires the script to stop immediately.

is_odd(){ 
  x=$1
  if [ $((x%2)) == 0 ]; then
     echo "Invalid Input"
     exit 1
  else
     echo "Number is Odd"
  fi
}
is_odd 64

Output:

Explanation: The function ‘is_odd()’ checks if a number is odd. If it’s even, it outputs an error message and exits the script using ‘exit 1’.

3. The functions that alter the value of a variable or variables.

These functions can modify the values of variables directly within their scope or globally if the variables are defined outside the function.

a=1
increment(){ 
  a=$((a+1))
  return
}
increment
echo "$a"

Output:

 

Explanation: The function ‘increment()’ increases the value of the variable ‘a’ by 1, demonstrating how functions can directly alter variable values.

4. The functions that echo output to the standard output.

These functions output information directly to the standard output using the ‘echo’ command.

hello_world(){ 
  echo "Hello World"
  return
}
hello_world

Output:

Explanation: The function ‘hello_world()’ simply prints “Hello World” to the standard output, illustrating a basic use of echoing in functions.

Conclusion

Functions in shell scripting are essential for creating modular, readable, and maintainable code. They allow you to encapsulate tasks into reusable blocks, making scripts more efficient and easier to manage. These various types of functions provide the shell scripting skills and create robust scripts that handle complex tasks with ease.



Next Article
Article Tags :

Similar Reads