shopt: Enabling Bash-Specific Options

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

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

OptionEffect when on
inherit_errexitcommand substitutions keep set -e (lesson 121)
expand_aliasesaliases work in scripts (lesson 144)
globasciiranges[a-z] means ASCII letters only, whatever the locale (on by default)
localvar_inherita new local variable starts with the value of the outer one (lesson 93)
sourcepathsource searches PATH for the file (on by default, lesson 95)
nullglob, failglob, dotglob, globstar, extglob, nocaseglob, nocasematch, lastpipedescribed above

Options for the Interactive Shell

Some options matter only at the prompt and belong in ~/.bashrc (lesson 146):

OptionEffect when on
histappendappend to the history file instead of overwriting it
cmdhistsave a multi-line command as one history entry (on by default)
checkwinsizeupdate LINES and COLUMNS after each command (on by default since Bash 5.0)
autocdtyping a folder name alone changes into it
cdspellcd corrects small spelling mistakes in folder names
dirspelltab completion corrects spelling mistakes in folder names
checkjobswarn 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 -s line stands on its own line near the top, before the loop that uses @(...) is read, as extglob requires.
  • **/*.@(sh|py|js|c|h) combines globstar and extglob: any file at any depth whose name ends in one of the five extensions. nocaseglob makes the match ignore case.
  • Hidden folders such as .git or .cache are skipped automatically, because dotglob is 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 a node_modules folder at the top level.
  • [[ -f $path ]] skips folders whose names happen to end in an extension, such as a folder called tools.js.
  • ${ext,,} converts the extension to lower case, so PY and py are counted together. Two associative arrays (lesson 102) hold the file and line counts per extension.
  • nullglob makes 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.

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 shopt: Enabling Bash-Specific Options and get answers drawn from it.

Signed-in readers only.