Friday, April 17, 2009

Functions in shell script

Functions are the series of commands/ instructions. Within shell script, you can create function. In fact to do a particular type of task we can create function and later we can call them inside shell script. Thus to organize code within shell script function is used.

The syntax to define a function is,

my_function_name ()
{
series_of_commands
return
}


The function starts with a name immediately followed by parenthesis and braces. The function body resides between braces.

Function is not executed if you define it like above. In order to call the function just use the name of it. Like to call my_function_name just use
my_function_name

Here is an example of function usage.

# vi log_out.sh
logout ()
{
echo "Goodbye.."
echo "Press any key to logout ...."
read
return
}
echo "Hi $LOGNAME"
logout

# chmod +x log_out.sh

# sh log_out.sh
Hi root
Goodbye..
Press any key to logout ....

Related Documents

No comments:

Post a Comment