How to Use "functions" in Shell Scripts

When used in shell scripts, functions are a way of isolating a segment of code so that it can be called repeatedly without having to write the entire segment again. Additionally, if the code requires an update, the function’s content can be updated, and everywhere the function is referenced, the updated code is now executed.

An example of defining and using a function within a shell script follows, taken from /etc/ profile. The pathmunge function takes two arguments; the first is a directory, the second (optional) is the word “after”. Based on whether “after” is passed as $2, the directory will be added to the PATH environment variable at the front or end of the existing list of directories. Later, the function is invoked several times to build the PATH for root or regular users. Notice that for root, all the directories are prepended to PATH, where regular users have their PATH built by appending.

pathmunge () {
  if [ "$2" = "after" ] ; then
    PATH=$PATH:$1
  else
    PATH=$1:$PATH
  fi
}
...
if [ "$EUID" = "0" ]; then
    pathmunge /sbin
    pathmunge /usr/sbin
    pathmunge /usr/local/sbin
else
    pathmunge /usr/local/sbin after
    pathmunge /usr/sbin after
    pathmunge /sbin after
fi

Functions can also be set in the bash shell environment. When set in the environment, they can be executed as commands on the command line, similar to aliases. Unlike aliases, they can take arguments, be much more sophisticated in their actions, and provide a return code. Functions can be defined in the current shell by typing them into the command line, but more realistically, they should be set in a user’s ~/.bashrc or the global /etc/bashrc.

There are many functions set by default in the user environment, which can be viewed with the set command. set will display all functions and variables in the current shell environment. To remove a function from the environment, a user or administrator may use the unset command, passing the function or variable name to remove.