Shell Functions 13. Shell Functions General Format: name() { command; ...; command; } or name() { command ... command } The body of the function is within the braces, each command separated by a semicolon if on the same line. The name of the function has the same legal characters as variable names. They are in the same space! These commands defined will be executed whenever the function is executed. 14. Examples: $ nu () { who | wc -l; } $ nu 22 $ la () { ls -a "$@"; } $ lf () { ls -F "$@"; } $ la -lt $ lf -alist * 15. Arguments to a function are referenced in the function by the shell parameters $1, $2, ... as in shell scripts. Functions exist only in the shell in which they are defined. They cannot be passed down to subshells. Changes made to the current directory or to variable values remain after the function has completed execution. 16. Another Example $ db() { > PATH=$PATH:/usr/data > PS1=RK: > cd /usr/data; > } $ db RK: 17. Advantages to functions: (1) once defined [in memory], it is faster than an equivalent shell script (2) you can group all of your related shell functions in a single file (3) Variable values from calling programs are automatically available 18. Removing a function definition: $ unset functionname 19. To provide a success/failure status to the function, use the shell builtin command: returnQuestions? Robert Katz: katz@ned.highline.edu# n=0 means successful status # n non-zero means unsuccessful status