The Bourne-again shell is a Unix shell written for the GNU Project. Its ubiquity on Unix and Linux systems makes it a powerful tool for writing scripts to perform tedious actions (e.g. moving and modifying files).

Resource Progress Division
Bash Guide for Beginners -/12 Chapters
Advanced Bash-Scripting Guide 3/37 Chapters
GNU Bash Reference Manual -/10 Sections
IBM Bash By Example, Part 1 1/3 Parts
Learning the bash Shell 1 -/12 Chapters

Set an environment variable for a command

An environment variable can be localized to a single command if it’s declaration is prepended to the command. For example,

$ CFLAGS="-Wall" make script

passes the moifier, -Wall, to the make command.

Mimic C++ namespacing

Use :: like the scope resolution operator in C++. Although it doesn’t provide namespacing it can still be used to associate a function with a library.

Disable -x in a logging function

Bash 4.4 added support for setting options locally within a function using local -.

function log_error {
  { local -; set +x; } 2> /dev/null  # Silently disable xtrace
  # Handle logging
}

Error handling using a subshell

It is possible to simplify error handling using a subshell, however it does come with significant drawbacks.

function create_file_on_dev {
    local device="${1}"
    local path="${1}"

(   set -e
    mount "${device}" /mnt
    trap "umount /mnt" EXIT

    touch "/mnt/${path}"
); return $?
}

In this example we do not need to check the exit code of each command since set -e will exit immediately from the subshell. The return $? statement will return the exit code of that command from the function. Additionally we can trap on EXIT to do some clean-up (e.g. guarantee that the device is unmounted) even if a following command fails.

This pattern works well for many cases, but causes scoping issues when modifying globals. It cannot be used if you’re using the additional 3-9 file descriptors.

Additional resources


  1. Newham, Cameron and Bill Rosenblatt. Learning the bash Shell. 3rd ed. Cambridge: O’Reilly, 2005.↩︎