Thursday, 25 April 2013

Unix Shell Script :How to Use functions


User defined functions can be created in shell scripts. Syntax for creating a function is :

Syntax:
function_name()
{
#code
}

Functions needs to be created before they are called.

Syntax for calling a function in shell script is :

function_name arg1 arg2

Also, command line arguments works similarly they work in shell  scripts. So $1 would be the first argument inside the function , $2 would be the second argument and so on.

Following is an example shell script which contains a fucntion "func()" :

$ cat testfunction.sh
#!/bin/bash
func()
{
echo $1
}
func hello

$ ./testfunction.sh
hello

No comments:

Post a Comment