Next: , Previous: Special Shell Variables, Up: Portable Shell


10.11 Shell Functions

Nowadays, it is difficult to find a shell that does not support shell functions at all. However, some differences should be expected:

Inside a shell function, you should not rely on the error status of a subshell if the last command of that subshell was exit or trap, as this triggers bugs in zsh 4.x; while Autoconf tries to find a shell that does not exhibit the bug, zsh might be the only shell present on the user's machine.

Likewise, the state of `$?' is not reliable when entering a shell function. This has the effect that using a function as the first command in a trap handler can cause problems.

     $ bash -c 'foo(){ echo $?; }; trap foo 0; (exit 2); exit 2'; echo $?
     2
     2
     $ ash -c 'foo(){ echo $?; }; trap foo 0; (exit 2); exit 2'; echo $?
     0
     2

Shell variables and functions may share the same namespace, for example with Solaris 10 /bin/sh:

     $ f () { :; }; f=; f
     f: not found

For this reason, Autotest uses the prefix `at_func_' for its functions.

Handling of positional parameters and shell options varies among shells. For example, Korn shells reset and restore trace output (`set -x') and other options upon function entry and exit. Inside a function, IRIX sh sets `$0' to the function name.

Some ancient Bourne shell variants with function support did not reset `$i, i >= 0', upon function exit, so effectively the arguments of the script were lost after the first function invocation. It is probably not worth worrying about these shells any more.

With AIX sh, a trap on 0 installed in a shell function triggers at function exit rather than at script exit, see See Limitations of Builtins.