Shell Options with set
Bash has a set of switches, called shell options, that change how the shell behaves: whether it stops on errors, whether it expands * into file names, whether > may overwrite files, whether every variable is exported automatically, and more. The set built-in turns these options on and off. Many of them come from the POSIX shell standard, so they work in sh, Dash and Bash alike.
Earlier lessons used a few of them already: set -e (lesson 119), set -u and set -o pipefail (lesson 120) and set -x (lesson 126). This lesson explains how set works in general, how to inspect and restore options, and covers the other options that are useful in scripts and at the prompt. (Bash-specific options are controlled by a different command, shopt, which lesson 149 covers.)
The Syntax of set
set -X # turn option X on (single letter)
set +X # turn option X off
set -o NAME # turn option NAME on (long name)
set +o NAME # turn option NAME off
set -o # list all options with on/off
set +o # print the commands that recreate the current settings
The logic of - for on and + for off is the opposite of what many people expect: think of - as "add this flag" and + as "remove it". Several options can be combined: set -euo pipefail turns on -e, -u and the long option pipefail in one command, and set -o errexit -o nounset does the same with long names.
set has two other jobs, which are unrelated to options:
setwith no arguments prints every shell variable and function, which is mainly useful withgrep;set -- ARGSreplaces the positional parameters$1,$2, ... (lesson 44).
greeting=hello
set | grep -E '^(greeting|BASH_VERSION)='
set -- red green blue; echo "$# args: $*"
set --; echo "$# args"
BASH_VERSION='5.2.21(1)-release'
greeting=hello
3 args: red green blue
0 args
The same options can be given when starting Bash: bash -x script.sh or bash -o pipefail script.sh run the script with those options on from the first line.
The Most Useful Options
| Short | Long name | When on |
|---|---|---|
-e | errexit | stop when a command fails (lesson 119) |
-u | nounset | treat unset variables as errors (lesson 120) |
pipefail | a pipeline fails if any part fails (lesson 120) | |
-x | xtrace | print each command before running it (lesson 126) |
-v | verbose | print each input line as it is read |
-n | noexec | read commands but do not run them |
-f | noglob | do not expand *, ? and [...] |
-C | noclobber | > refuses to overwrite existing files |
-a | allexport | export every variable that is assigned |
-B | braceexpand | brace expansion {a,b} (on by default) |
-P | physical | cd and pwd resolve symbolic links |
-m | monitor | job control (on in interactive shells, lesson 137) |
-b | notify | report ended background jobs immediately (lesson 137) |
-h | hashall | remember where commands were found (on by default) |
-H | histexpand | ! history expansion (on in interactive shells) |
-E | errtrace | ERR traps are inherited by functions (lesson 123) |
-T | functrace | DEBUG and RETURN traps are inherited by functions |
ignoreeof | Ctrl+D does not close the shell | |
vi, emacs | key bindings for command-line editing | |
posix | follow the POSIX standard where Bash differs |
Inspecting the Current Options
There are three ways to see which options are on.
set -o lists every long option with its state:
set -o | head -5
allexport off
braceexpand on
emacs off
errexit off
errtrace off
(This output comes from a script; in an interactive shell, emacs is on, because Readline editing is active.)
$- holds the letters of the active single-letter options, and SHELLOPTS lists the active long names separated by colons. Both are read-only views:
set -C; echo "$-"; echo "$SHELLOPTS"; set +C
hBC
braceexpand:hashall:interactive-comments:noclobber
set +o prints a set command for every option, in a form the shell can read back:
set +o | grep -E 'noclobber|noglob|errexit'
set +o errexit
set +o noclobber
set +o noglob
Asking for an option that does not exist is an error with status 2:
t148.sh: line 29: set: nosuch: invalid option name
status 2
t148.sh: line 29: set: -q: invalid option
set: usage: set [-abefhkmnptuvxBCEHPT] [-o option-name] [--] [-] [arg ...]
status 2
Options for Safer Scripts
noclobber: -C
The > redirection empties a file before writing to it, so a typing mistake can destroy data. With set -C, > refuses to write to an existing regular file. Appending with >> still works, and >| overwrites on purpose:
echo one > note.txt
set -C
echo two > note.txt
echo "status $?"; cat note.txt
echo three >> note.txt; echo four >| note.txt; cat note.txt
set +C
t148.sh: line 8: note.txt: cannot overwrite existing file
status 1
one
four
The refused redirection is a failure with status 1, so the command (echo two) did not run and note.txt kept one. >> appended three, and >| then overwrote the whole file with four. Many people turn on set -o noclobber in ~/.bashrc as protection at the prompt; in scripts, it guards files that must never be replaced by accident.
noglob: -f
set -f turns off filename expansion, so *, ? and [...] stay literal. This matters when a script processes text that may contain these characters, such as user input or patterns that should be passed on unchanged. The test folder contains a.txt and b.txt:
echo *.txt
set -f; echo *.txt; set +f; echo *.txt
set -o noglob; echo "$-"; set +o noglob; echo "$-"
a.txt b.txt
*.txt
a.txt b.txt
fhB
hB
set -o noglob is the long name of the same option, as the f in $- shows. Quoting (lesson 55) is usually the better tool to stop expansion of a single word; set -f helps when unquoted word splitting is wanted but filename expansion is not, for example when splitting a string on spaces into an array.
noexec: -n
set -n, and more commonly bash -n script.sh, reads commands without running them. It is a syntax check:
# broken.sh: the if is never closed
echo ok
if true; then
echo inside
bash -n broken.sh; echo "bash -n status $?"
broken.sh: line 4: syntax error: unexpected end of file
bash -n status 2
Nothing was printed by echo ok: the file was only parsed. When set -n is written inside a script, every following line is parsed and skipped, and an interactive shell ignores set -n completely, so that you cannot lock yourself out of your own terminal.
verbose: -v
set -v prints each line exactly as Bash reads it, before any expansion. set -x (lesson 126) prints commands after expansion. The difference is easy to see:
set -v
x=5; echo "x is $x"
set +v
x=5; echo "x is $x"
x is 5
set +v
The whole line was shown once, with $x unexpanded, followed by its output. The set +v line itself was also printed, because it was read while the option was still on.
Exporting Automatically: -a
With set -a (allexport), every variable that is assigned is also exported to child processes. The most common use is loading a configuration file of KEY=value lines so that the programs you start can see the values:
set -a; city=Chennai; port=8080; set +a; country=India
bash -c 'echo "child sees: city=$city port=$port country=$country"'
child sees: city=Chennai port=8080 country=
city and port were assigned while the option was on and reached the child shell; country was assigned after set +a and stayed local. The complete example at the end uses this technique.
Brace Expansion and Physical Paths
-B is on by default. Turning it off makes {...} literal:
echo {1..3}; set +B; echo {1..3}; set -B
1 2 3
{1..3}
-P changes how cd treats symbolic links. In the test folder, shortcut is a link to real/data:
cd /home/ana/s148
cd shortcut; pwd; cd ..; pwd
set -P
cd shortcut; pwd; cd ..; pwd
set +P
/home/ana/s148/shortcut
/home/ana/s148
/home/ana/s148/real/data
/home/ana/s148/real
By default, Bash remembers the path you used ("logical" path), so pwd shows shortcut and cd .. goes back to where you came from. With -P, Bash resolves the link to the real folder, and cd .. goes to the real parent, real, not to the folder that contains the link. cd -P and pwd -P give the physical behavior for a single command.
ignoreeof at the Prompt
Pressing Ctrl+D at an empty prompt ends the shell, which can close an SSH session by accident. set -o ignoreeof prevents this:
$ set -o ignoreeof
$
Use "exit" to leave the shell.
$ echo still here
still here
$ IGNOREEOF=0
$
exit
Ctrl+D (shown as an empty line) printed a reminder instead of closing the shell. The option works through the variable IGNOREEOF, the number of Ctrl+D presses Bash ignores (10 when the option is turned on); setting it to 0 let the next Ctrl+D end the shell. This option is meant for ~/.bashrc, not scripts.
Changing Options for a Short Time
Options are global: an option turned on inside a function stays on after the function returns. Two techniques limit the change.
local - inside a function saves all single-letter options and restores them when the function returns:
quiet_glob() {
local -
set -f
echo "inside: $- ->" *.txt
}
quiet_glob
echo "outside: $- ->" *.txt
inside: fhB -> *.txt
outside: hB -> a.txt b.txt note.txt
A subshell ( ... ) runs in a copy of the shell, so options changed inside it disappear when it ends:
( set -f; echo *.txt ); echo *.txt
*.txt
a.txt b.txt note.txt
Saving with saved=$(set +o) and restoring with eval "$saved" also exists, but lesson 121 showed that the saved text can miss errexit; local - and subshells are simpler.
A Complete Example: Running a Command with an Environment File
Projects often keep their settings in a file of KEY=value lines, such as app.env. The script below loads such a file, exports every variable in it with set -a, and runs a command with that environment. It combines several options: -e, -u and pipefail for safety, -x on request, -n to check the file before using it, and -a for the export.
#!/usr/bin/env bash
# with-env.sh: run a command with the variables of an env file exported
# usage: with-env.sh ENV_FILE COMMAND [ARG...]
# The env file holds Bash assignments (KEY=value) and comments. It is
# sourced, so it must come from a trusted source.
set -euo pipefail # stop on errors, unset names, pipe failures
[[ ${TRACE:-} == 1 ]] && set -x # TRACE=1 shows each step
prog=${0##*/}
if (( $# < 2 )); then
echo "usage: $prog ENV_FILE COMMAND [ARG...]" >&2
exit 2
fi
env_file=$1
shift
if [[ ! -f $env_file || ! -r $env_file ]]; then
echo "$prog: cannot read env file: $env_file" >&2
exit 1
fi
if ! bash -n "$env_file"; then # -n: parse only, run nothing
echo "$prog: syntax error in $env_file, nothing was run" >&2
exit 1
fi
set -a # export every variable assigned from here
source "$env_file"
set +a # back to normal: new variables stay local
exec "$@" # replace this script with the command
The environment file used in the tests:
# settings for the reporting job
DB_HOST=localhost
DB_PORT=5432
REPORT_TITLE="Monthly Sales Report"
How It Works
set -euo pipefailmakes the script stop at the first problem instead of running the command with half-loaded settings.[[ ${TRACE:-} == 1 ]] && set -xturns on tracing only when the caller asks for it withTRACE=1. The:-default keepsset -ufrom complaining whenTRACEis not set.bash -n "$env_file"starts a second Bash that only parses the file. A missing quote or an unclosedifis reported before anything is loaded or run.set -a...set +asurround thesourcecommand, so exactly the variables assigned in the file are exported. Variables of the script itself, such asprogandenv_file, were assigned earlier and are not exported.exec "$@"replaces the script with the command (execstarts the command in place of the current shell process instead of as a child). The command inherits the exported variables, and its exit status becomes the status ofwith-env.sh.- Because the file is sourced, any command in it runs. That is why the comment says the file must be trusted; lesson 157 discusses this kind of risk.
Running the Complete Example
Different programs read the exported values: env, a Python program and a Bash child:
./with-env.sh app.env env | grep -E '^(DB_|REPORT_)' | sort
./with-env.sh app.env python3 -c 'import os; print(os.environ["REPORT_TITLE"], os.environ["DB_PORT"])'
./with-env.sh app.env bash -c 'echo "$REPORT_TITLE on $DB_HOST:$DB_PORT"'
DB_HOST=localhost
DB_PORT=5432
REPORT_TITLE=Monthly Sales Report
Monthly Sales Report 5432
Monthly Sales Report on localhost:5432
For comparison, sourcing the same file without set -a leaves the variables in the shell, invisible to programs:
bash -c 'source ./app.env; python3 -c "import os; print(os.environ.get(\"DB_HOST\", \"not exported\"))"'
not exported
Error cases: a missing file, a file with an unclosed quote (bad.env contains REPORT_TITLE="unterminated), too few arguments, and a command that fails:
$ ./with-env.sh nope.env env; echo "status $?"
with-env.sh: cannot read env file: nope.env
status 1
$ ./with-env.sh bad.env env; echo "status $?"
bad.env: line 2: unexpected EOF while looking for matching `"'
with-env.sh: syntax error in bad.env, nothing was run
status 1
$ ./with-env.sh app.env; echo "status $?"
usage: with-env.sh ENV_FILE COMMAND [ARG...]
status 2
$ ./with-env.sh app.env ls /nope; echo "status $?"
ls: cannot access '/nope': No such file or directory
status 2
The syntax check caught the broken file before it was sourced. The last status, 2, is the status of ls, passed through by exec.
With TRACE=1, set -x shows every step; the lines with ++ come from inside the sourced file:
$ TRACE=1 ./with-env.sh app.env true
+ prog=with-env.sh
+ (( 2 < 2 ))
+ env_file=app.env
+ shift
+ [[ ! -f app.env ]]
+ [[ ! -r app.env ]]
+ bash -n app.env
+ set -a
+ source app.env
++ DB_HOST=localhost
++ DB_PORT=5432
++ REPORT_TITLE='Monthly Sales Report'
+ set +a
+ exec true