Menu

UNIX TUTORIALS - Unix - Shell Functions

Unix - Shell Functions

ADVERTISEMENTS

Creating Functions:

function_name () { 
   list of commands
}

ADVERTISEMENTS

Example:

#!/bin/sh

# Define your function here
Hello () {
   echo "Hello World"
}

# Invoke your function
Hello

ADVERTISEMENTS

$./test.sh
Hello World
$

Pass Parameters to a Function:

#!/bin/sh

# Define your function here
Hello () {
   echo "Hello World $1 $2"
}

# Invoke your function
Hello Zara Ali

$./test.sh
Hello World Zara Ali
$

Returning Values from Functions:

return code

Example:

#!/bin/sh

# Define your function here
Hello () {
   echo "Hello World $1 $2"
   return 10
}

# Invoke your function
Hello Zara Ali

# Capture value returnd by last command
ret=$?

echo "Return value is $ret"

$./test.sh
Hello World Zara Ali
Return value is 10
$

Nested Functions:

#!/bin/sh

# Calling one function from another
number_one () {
   echo "This is the first function speaking..."
   number_two
}

number_two () {
   echo "This is now the second function speaking..."
}

# Calling function one.
number_one

This is the first function speaking...
This is now the second function speaking...

Function Call from Prompt:

$. test.sh

$ number_one
This is the first function speaking...
This is now the second function speaking...
$

$unset .f function_name