Shell Options with set

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 148 of 205

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:

  • set with no arguments prints every shell variable and function, which is mainly useful with grep;
  • set -- ARGS replaces 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

ShortLong nameWhen on
-eerrexitstop when a command fails (lesson 119)
-unounsettreat unset variables as errors (lesson 120)
pipefaila pipeline fails if any part fails (lesson 120)
-xxtraceprint each command before running it (lesson 126)
-vverboseprint each input line as it is read
-nnoexecread commands but do not run them
-fnoglobdo not expand *, ? and [...]
-Cnoclobber> refuses to overwrite existing files
-aallexportexport every variable that is assigned
-Bbraceexpandbrace expansion {a,b} (on by default)
-Pphysicalcd and pwd resolve symbolic links
-mmonitorjob control (on in interactive shells, lesson 137)
-bnotifyreport ended background jobs immediately (lesson 137)
-hhashallremember where commands were found (on by default)
-Hhistexpand! history expansion (on in interactive shells)
-EerrtraceERR traps are inherited by functions (lesson 123)
-TfunctraceDEBUG and RETURN traps are inherited by functions
ignoreeofCtrl+D does not close the shell
vi, emacskey bindings for command-line editing
posixfollow 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 pipefail makes the script stop at the first problem instead of running the command with half-loaded settings.
  • [[ ${TRACE:-} == 1 ]] && set -x turns on tracing only when the caller asks for it with TRACE=1. The :- default keeps set -u from complaining when TRACE is not set.
  • bash -n "$env_file" starts a second Bash that only parses the file. A missing quote or an unclosed if is reported before anything is loaded or run.
  • set -a ... set +a surround the source command, so exactly the variables assigned in the file are exported. Variables of the script itself, such as prog and env_file, were assigned earlier and are not exported.
  • exec "$@" replaces the script with the command (exec starts 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 of with-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

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Shell Options with set and get answers drawn from it.

Signed-in readers only.