Functions in Shell Script
When program gets more complex we divide it into small modules or entities which is know as function. It is series of instruction or commands statements. Function performs some particular activities in shell programs i.e. it had specific task to do.
Syntax:
function_name( )
{
command_statement1
command_statement2
.....
...
command_statementN
return
}
Where function_name is the name of your function, that executes series of many commands and a return statement terminates the function.
Example:
$ name = "Sunni!"
Type SayHi() at $ prompt as follows
$ SayHello()
{
echo "Hello $name, How are you?"
return
}
To execute this Function SayHello() just type it's name as follows:
Output :
This way we can call function. Note that after restarting your terminal you will loss this function, because its created for current the session only.
To overcome this problem we can save this fucntion in a file for future use.
The given script will create the function today() and print the current date.
today()
{
echo This is a `date +"%A %d in %B of %Y (%r)"`
return
}
today
0 Comments:
Post a Comment