The set builtin command is one of the most misunderstood (and overloaded!) commands in Bash. It does several different things depending on how it's called: show names, set shell options, and set shell positional parameters.
First of all, when run on its own with no arguments, set prints a list of all of the variables and any functions for the running shell, in alphabetical order. It includes the full definition of the functions. This is one of several ways to view all of the variables in the shell. We suggest you use declare instead, explained later in this chapter, as it shows more information about properties of the variables.
Secondly, set allows you to specify certain options for how the shell runs, all options starting with a single dash, -. The complete list of the options that can be set is too long to explain here, but is available in help set. Some options of note:
-
-e: Exit immediately if a command exits with a non-zero status. This is used in scripts as a way to stop running the script if anything goes wrong. Because this option's behavior can be hard to predict, it's generally better to write your own error-handling for all but the most simple scripts.
-
-n: Read commands but don't execute them. This is a useful way to check that your Bash script is syntactically correct without actually running any of the commands. Note that this is not perfect, however; some subtle properties of the Bash syntax can change during a script run, and the -n option might not catch that.
-
-v: Print shell input lines as they are read. This can be good for debugging, but does not show as much information as -x.
-
-x: Print commands and their arguments as they are executed. Turning this option on is often a very good first step for debugging a Bash script, as it shows you how the bash program has interpreted and expanded its input.
These options work the same way as if you had started the bash program with that option; for example, set -x in the shell has the same effect as starting the shell as bash -x, or having a script's shebang line include the option, such as #!/bin/bash -x.
Finally, set followed by the option terminator string, --, can be used to set the positional parameters for the shell. We will examine these special parameters in more detail in Chapter 6, Loops and Conditionals.