< Day Day Up > |
Although the Bourne shell does not have an alias mechanism for abbreviating commands, it does support functions (introduced to the shell in SVR2). Functions are used to execute a group of commands with a name . They are like scripts, only more efficient. Once defined, they become part of the shell's memory so that when the function is called, the shell does not have to read it in from the disk as it does with a file. Often functions are used to improve the modularity of a script (discussed in the programming section of this chapter). Once defined, they can be used again and again. Functions are often defined in the user 's initialization file, .profile . They must be defined before they are invoked, and cannot be exported. 7.9.1 Defining FunctionsThe function name is followed by a set of empty parentheses. The definition of the function consists of a set of commands separated by semicolons and enclosed in curly braces. The last command is terminated with a semicolon. Spaces around the curly braces are required. FORMAT function_name () { commands ; commands; } Example 7.35.1 $ greet () { echo "Hello $LOGNAME, today is `date`; } 2 $ greet Hello ellie, today is Thu Oct 21 19:56:31 PDT 2004 EXPLANATION
Example 7.36.1 $ fun () { pwd; ls; date; } 2 $ fun /home/jody/ellie/prac abc abc123 file1.bak none nothing tmp abc1 abc2 file2 nonsense nowhere touch abc122 file1 file2.bak noone one Sat Feb 21 11:15:48 PST 2004 3 $ welcome () { echo "Hi and "; } 4 $ welcome tom joe Hi tom and joe 5 $ set jane nina lizzy 6 $ echo $* jane nina lizzy 7 $ welcome tom joe hi tom and joe 8 $ echo jane nina EXPLANATION
7.9.2 Listing and Unsetting FunctionsTo list functions and their definitions, use the set command. The function and its definition will appear in the output, along with the exported and local variables. Functions and their definitions are unset with the unset command. |
< Day Day Up > |