Functions in Bash

Functions in Bash

 Functions in Bash

A function that can also be referred to as a subroutine or procedure is a block of code used for specific tasks. The function also has a property called re-usability. Bash script also provides functions.

Syntax:

funcationName(){    
  // scope of function
}
functionName  //calling of function

1. Bash – Create Function Example

Create your first function in shell script showing the output “Hello World!”. Create a shell script “script.sh” using the following code.

#!/bin/bash

funHello(){
    echo "Hello World!";
}
# Call funHello from anywhere in the script like below
funHello

Let execute script

$ ./script.sh
Hello World!

2. Bash – Function with Argument

Passing an argument to functions is similar to passing an argument to a command from the shell. Functions receive arguments to $1,$2… etc. Create a shell script using the following code.

#!/bin/bash
funArguments(){
   echo "First Argument : " $1
   echo "Second Argument: " $2
   echo "Third Argument:  " $3
   echo "Fourth Argument: " $4
}
# Call funArguments from anywhere in the script using parameters like below
funArguments 1 Welcome to TecAdmin 

Let’s execute the script with the bash shell.

$ ./script.sh
First Argument  : 1
Second Argument : Welcome
Third Argument  : to
Fourth Argument : TecAd,om
Reactions

Post a Comment

0 Comments

close