shopt: Enabling Bash-Specific Options
shopt (shell options) is the Bash built-in that controls Bash's own options. Lesson 148 showed set, which manages the options defined by the POSIX shell standard, such as errexit and noclobber. Bash adds about fifty more options of its own, and these are managed with shopt. They decide, among other things, whether an unmatched *.log disappears or stays literal, whether * includes hidden files, whether ** searches subfolders, whether patterns ignore upper and lower case, and how history is saved.
Several of these options appeared in earlier lessons: extglob (lesson 76), nullglob and dotglob (lesson 82), expand_aliases (lesson 144), inherit_errexit (lesson 121) and lastpipe (lesson 83). This lesson explains the shopt command itself and groups the options that matter in practice.
The Syntax of shopt
shopt # list all Bash options with on/off
shopt NAME... # show the state of these options
shopt -s NAME... # set: turn options on
shopt -u NAME... # unset: turn options off
shopt -q NAME... # quiet: no output, status 0 only if all are on
shopt -p [NAME...] # print as shopt commands that recreate the settings
shopt -o NAME # work on a set -o option instead
Note the letters: -s for set and -u for unset, unlike set, which uses - and +. A Bash 5.2 shell lists 57 options:
shopt | wc -l
57
Asking for the state of one option, and turning several on at once:
shopt nullglob
shopt -s nullglob globstar; shopt nullglob globstar; shopt -u nullglob globstar
nullglob off
nullglob on
globstar on
An unknown name is an error with status 1:
t149b.sh: line 25: shopt: nosuchopt: invalid shell option name
status 1
Testing and Printing Options
shopt -q prints nothing and only sets the exit status, which makes it the right tool in conditions:
shopt -q nullglob && echo on || echo "off (status $?)"
off (status 1)
shopt -p prints each option as a shopt command:
shopt -p nullglob globstar extglob
shopt -u nullglob
shopt -u globstar
shopt -u extglob
shopt -o reaches the set -o options, so shopt -so noclobber is the same as set -o noclobber:
shopt -o noclobber; shopt -so noclobber; echo "$-"; shopt -uo noclobber
noclobber off
hBC
The active shopt options are also listed, separated by colons, in the read-only variable BASHOPTS, just as SHELLOPTS lists the active set -o options. Options can be turned on when Bash starts with -O NAME:
bash -O globstar -c 'cd src; echo **/*.c'
bash -O nullglob -c 'echo "$BASHOPTS"'
app/ui.c lib/util.c main.c
checkwinsize:cmdhist:complete_fullquote:extquote:force_fignore:globasciiranges:globskipdots:hostcomplete:interactive_comments:nullglob:patsub_replacement:progcomp:promptvars:sourcepath
The second line shows the options that are on by default in a Bash 5.2 script, plus nullglob.
Globbing Options
Most shopt options used in scripts control filename expansion (globbing, lesson 52). The examples use a test folder with these files:
.env notes.txt report.TXT src/main.c src/app/ui.c src/lib/util.c
nullglob and failglob: When Nothing Matches
By default, a pattern that matches nothing is left as it is. In a loop, this produces one bogus iteration:
for f in *.log; do echo "got: $f"; done
shopt -s nullglob
for f in *.log; do echo "got: $f"; done; echo "loop done"
shopt -u nullglob
got: *.log
loop done
With nullglob, the unmatched pattern disappears, and the loop body does not run at all. This is what a script usually wants. One caution: with nullglob, a command such as ls *.log receives no arguments when nothing matches, and ls then lists the whole current folder.
failglob turns an unmatched pattern into an error instead. Its effect in a script is stronger than many people expect:
shopt -s failglob
echo "before"
echo *.log; echo "same line after the failed glob"
echo "next line, status $?"
if ls *.log; then echo yes; else echo "if: else branch"; fi
echo "after if"
for f in *.log; do echo "$f"; done
echo "after for"
shopt -u failglob
before
t149b.sh: line 4: no match: *.log
next line, status 1
t149b.sh: line 7: no match: *.log
after if
t149b.sh: line 9: no match: *.log
after for
When the pattern failed, Bash abandoned the rest of that line: the second echo on line 4 did not run, and on line 7 neither branch of the if ran, not even else. Execution continued on the next line with status 1. failglob is therefore a good safety net at the prompt (a mistyped pattern is reported instead of being passed to a command), but in scripts nullglob with an explicit check for an empty result is easier to reason about.
dotglob: Hidden Files
* normally skips names that start with a dot. dotglob includes them (. and .. are never matched):
echo *; shopt -s dotglob; echo *; shopt -u dotglob
notes.txt report.TXT src
.env notes.txt report.TXT src
nocaseglob: Ignoring Case in File Names
echo *.txt; shopt -s nocaseglob; echo *.txt; shopt -u nocaseglob
notes.txt
notes.txt report.TXT
globstar: Recursive Matching with **
With globstar, ** matches any number of folder levels, including none. **/ matches only folders:
echo src/**/*.c; shopt -s globstar; echo src/**/*.c; echo **/; shopt -u globstar
src/app/ui.c src/lib/util.c
src/app/ui.c src/lib/util.c src/main.c
src/ src/app/ src/lib/
Without globstar, ** behaves like *, so src/**/*.c matched only files exactly one folder deep and missed src/main.c. With the option, it found the .c files at every level. For very large folder trees, find (lesson 20) is faster and offers more conditions, but globstar is convenient for loops in scripts.
extglob: Extended Patterns
extglob adds the patterns ?(...), *(...), +(...), @(...) and !(...) (lesson 76). It has a special requirement: Bash checks the syntax of these patterns when it reads a line, so the option must be on before the line that uses them is read. On the same line, it is too late:
shopt -s extglob; echo !(*.c)
t149d.sh: line 1: syntax error near unexpected token `('
t149d.sh: line 1: `shopt -s extglob; echo !(*.c)'
On its own line, before the use, it works (run in src):
shopt -s extglob
cd /home/ana/s149/src
echo !(*.c)
app lib
The same applies to functions: shopt -s extglob must run before the function definition is read, not inside the function.
Matching and Other Script Options
nocasematch
nocasematch makes [[ == ]], =~ and case patterns ignore case (lesson 75):
ans=YES; [[ $ans == yes ]] && echo match || echo "no match"
shopt -s nocasematch; [[ $ans == yes ]] && echo match || echo "no match"; shopt -u nocasematch
no match
match
lastpipe
Every part of a pipeline normally runs in a subshell, so variables changed in a while read loop at the end of a pipe are lost (lesson 83). lastpipe runs the last part in the current shell. It works only when job control is off, which is always the case in scripts:
count=0; printf 'a\nb\n' | while read -r l; do count=$((count+1)); done; echo "without: $count"
shopt -s lastpipe
count=0; printf 'a\nb\n' | while read -r l; do count=$((count+1)); done; echo "with: $count"
without: 0
with: 2
xpg_echo
xpg_echo makes echo interpret backslash sequences such as \t without -e, as the POSIX standard describes:
echo 'a\tb'; shopt -s xpg_echo; echo 'a\tb'; shopt -u xpg_echo
a\tb
a b
Because the same echo line can print different text depending on this option, printf (lesson 30) is the reliable choice in scripts.
Other Options for Scripts
| Option | Effect when on |
|---|---|
inherit_errexit | command substitutions keep set -e (lesson 121) |
expand_aliases | aliases work in scripts (lesson 144) |
globasciiranges | [a-z] means ASCII letters only, whatever the locale (on by default) |
localvar_inherit | a new local variable starts with the value of the outer one (lesson 93) |
sourcepath | source searches PATH for the file (on by default, lesson 95) |
nullglob, failglob, dotglob, globstar, extglob, nocaseglob, nocasematch, lastpipe | described above |
Options for the Interactive Shell
Some options matter only at the prompt and belong in ~/.bashrc (lesson 146):
| Option | Effect when on |
|---|---|
histappend | append to the history file instead of overwriting it |
cmdhist | save a multi-line command as one history entry (on by default) |
checkwinsize | update LINES and COLUMNS after each command (on by default since Bash 5.0) |
autocd | typing a folder name alone changes into it |
cdspell | cd corrects small spelling mistakes in folder names |
dirspell | tab completion corrects spelling mistakes in folder names |
checkjobs | warn about running jobs on exit (lesson 137) |
globstar | ** at the prompt, for example ls **/*.md |
autocd and cdspell in action, with \w (the current folder) in the prompt:
~/s149$ shopt -s autocd cdspell dirspell
~/s149$ src
cd -- src
~/s149/src$ cd /home/ana/s149
~/s149$ cd sr/lbi
src/lib
~/s149/src/lib$ shopt -u autocd
~/s149/src/lib$ src
bash: src: command not found
With autocd, typing src ran cd -- src, and Bash printed the command it used. cdspell corrected sr/lbi (one missing letter, two swapped letters) to src/lib and printed the corrected path. These corrections apply only in interactive shells.
Changing Options Temporarily
shopt options are global, and unlike set options, local - does not save them. A script library that turns on nullglob for one loop should restore the previous state afterwards. Because shopt -p prints commands, its output can be saved and run later:
old_ng=$(shopt -p nullglob) # "shopt -u nullglob"
shopt -s nullglob
# ... work that needs nullglob ...
$old_ng # runs "shopt -u nullglob"
shopt nullglob
nullglob off
Running $old_ng unquoted splits it into the words shopt, -u and nullglob, which form the original command. This works only for a single option. With several options, the saved text contains several lines, and running it unquoted joins all the words into one broken command:
t149.sh: line 18: shopt: shopt: invalid shell option name
t149.sh: line 18: shopt: -u: invalid shell option name
For several options, eval runs each saved line as a separate command. The text comes from shopt -p itself, not from a user, so this use of eval is safe (lesson 157 discusses when eval is risky):
saved=$(shopt -p nullglob dotglob)
shopt -s nullglob dotglob
eval "$saved"
shopt nullglob dotglob
nullglob off
dotglob off
A subshell ( ... ) is the other way to keep a change local: options set inside it disappear when it ends.
A Complete Example: Counting Source Code by Language
codestats.sh counts source files and lines per file extension in a project folder. It needs four shopt options: globstar to search all subfolders, extglob to match several extensions with one pattern, nocaseglob to include names such as Legacy.PY, and nullglob so that an empty folder gives an empty list.
#!/usr/bin/env bash
# codestats.sh: count source files and lines per extension under a folder
# usage: codestats.sh [DIR] (default: the current folder)
set -euo pipefail
# globstar: ** matches files in all subfolders
# extglob: @(a|b) matches one of several patterns
# nocaseglob: *.py also matches Legacy.PY
# nullglob: no matches gives an empty list, not the pattern itself
shopt -s globstar extglob nocaseglob nullglob
dir=${1:-.}
if [[ ! -d $dir ]]; then
echo "codestats: not a folder: $dir" >&2
exit 1
fi
cd -- "$dir"
declare -A files=() lines=()
for path in **/*.@(sh|py|js|c|h); do
case /$path in
*/node_modules/*) continue ;; # skip installed dependencies
esac
[[ -f $path ]] || continue
ext=${path##*.}
ext=${ext,,} # PY and py count together
n=$(wc -l < "$path")
files[$ext]=$(( ${files[$ext]:-0} + 1 ))
lines[$ext]=$(( ${lines[$ext]:-0} + n ))
done
if (( ${#files[@]} == 0 )); then
echo "No source files found in $dir"
exit 0
fi
printf '%-5s %5s %6s\n' EXT FILES LINES
for ext in "${!files[@]}"; do
printf '%-5s %5d %6d\n' "$ext" "${files[$ext]}" "${lines[$ext]}"
done | sort
How It Works
- The
shopt -sline stands on its own line near the top, before the loop that uses@(...)is read, asextglobrequires. **/*.@(sh|py|js|c|h)combinesglobstarandextglob: any file at any depth whose name ends in one of the five extensions.nocaseglobmakes the match ignore case.- Hidden folders such as
.gitor.cacheare skipped automatically, becausedotglobis off and**does not enter folders whose names start with a dot. case /$path in */node_modules/*skips installed dependencies. The leading/lets the pattern also match anode_modulesfolder at the top level.[[ -f $path ]]skips folders whose names happen to end in an extension, such as a folder calledtools.js.${ext,,}converts the extension to lower case, soPYandpyare counted together. Two associative arrays (lesson 102) hold the file and line counts per extension.nullglobmakes the loop run zero times in a folder without source files, so the "No source files" message appears instead of a count for a literal pattern.
Running the Complete Example
The test project proj contains Python files at three levels (one named Legacy.PY inside a folder with a space, old code), two shell scripts (deploy.sh and backup.SH), a JavaScript file, a 300-line node_modules/lib/index.js, a hidden .cache/tmp.py, a README.md, and an empty folder:
./codestats.sh proj; echo "status $?"
./codestats.sh proj/empty; echo "status $?"
./codestats.sh nope; echo "status $?"
(cd proj/scripts && ../../codestats.sh)
EXT FILES LINES
js 1 50
py 3 77
sh 2 48
status 0
No source files found in proj/empty
status 0
codestats: not a folder: nope
status 1
EXT FILES LINES
sh 2 48
The three Python files (40 + 25 + 12 lines) include Legacy.PY, found through nocaseglob; the two shell scripts include backup.SH. The node_modules file and the hidden .cache file were not counted, and the file name with a space caused no problem. The last run, without an argument, counted the current folder.
Removing the shopt line shows how much the script depends on it:
/tmp/cs2.sh: line 19: syntax error near unexpected token `('
/tmp/cs2.sh: line 19: syntax error near unexpected token `('
Without extglob, Bash cannot even parse the @(...) pattern, and the script fails before it runs; Bash printed the message twice.