A function is defined with the function command, a function name, open/close parentheses, and a function body enclosed in curly brackets:
- A function is defined as follows:
function fname()
{
statements;
}
Alternatively, it can be defined as:
fname()
{
statements;
}
It can even be defined as follows (for simple functions):
fname() { statement; }
- A function is invoked using its name:
$ fname ; # executes function
- Arguments passed to functions are accessed positionally, $1 is the first argument, $2 is the second, and so on:
fname arg1 arg2 ; # passing args
The following is the definition of the function fname. In the fname function, we have included various ways of accessing the function arguments.
fname()
{
echo $1, $2; #Accessing arg1 and arg2
echo "$@"; # Printing all arguments as list at once
echo "$*"; # Similar to $@, but arguments taken as single
entity
return 0; # Return value
}
Arguments passed to scripts can be accessed as $0 (the name of the script):
-
- $1 is the first argument
- $2 is the second argument
- $n is the nth argument
- "$@" expands as "$1" "$2" "$3" and so on
- "$*" expands as "$1c$2c$3", where c is the first character of IFS
- "$@" is used more often than $*, since the former provides all arguments as a single string
- Compare alias to function
- Here's an alias to display a subset of files by piping ls output to grep. The argument is attached to the end of the command, so lsg txt is expanded to ls | grep txt:
$> alias lsg='ls | grep'
$> lsg txt
file1.txt
file2.txt
file3.txt
- If we wanted to expand that to get the IP address for a device in /sbin/ifconfig, we might try the following:
$> alias wontWork='/sbin/ifconfig | grep'
$> wontWork eth0
eth0 Link encap:Ethernet HWaddr 00:11::22::33::44:55
- The grep command found the eth0 string, not the IP address. If we use a function instead of an alias, we can pass the argument to the ifconfig, instead of appending it to the grep:
$> function getIP() { /sbin/ifconfig $1 | grep 'inet '; }
$> getIP eth0
inet addr:192.168.1.2 Bcast:192.168.255.255 Mask:255.255.0.0