bash functions bash function arguments

Bash functions bash function arguments

Bash functions bash function arguments

functions in bash used to perform repetitive tasks , we can put all task or command in one function and we can used it by just calling function name.

Creating Functions

syntax

functionName () {
list of commands
}

#!/bin/sh

DisplayMe() {
echo "Hello all"
}

# using function name
DisplayMe

Output

Hello all

Bash function arguments

#!/bin/sh

DisplayMe () {
echo "Hi $1 $2"
}

DisplayMe ken corner

Output

Hi ken corner

Returning Values from Functions

#!/bin/sh

DisplayMe () {
echo "Hi $1 $2"
return 55
}

DisplayMe Ken corner
# Capture value returns by last command
returnValue=$?

echo "Function return value is $returnValue"

Output

Hi ken corner
Function return value is 55

Nested Functions

Nested function is function within function

Example

#!/bin/sh

# Calling one function from another
FunctionOne () {
echo -e "I am in Function One\n"
FunctionTwo
}

FunctionTwo () {
echo "I am in Fnction Two"
}

# Calling FunctionOne.
FunctionOne

Output

I am in Function One
I am in Fnction Two

Explanation : in the above example we can see that we only called FunctionOne and then FunctionOne called to FunctionTwo

 


You May Also Enjoy Reading This …

Leave a Reply

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