Skip to content

Instantly share code, notes, and snippets.

@detain
Created May 4, 2024 00:09
Show Gist options
  • Save detain/dfa0e4d75647b424c5aea45a34af0713 to your computer and use it in GitHub Desktop.
Save detain/dfa0e4d75647b424c5aea45a34af0713 to your computer and use it in GitHub Desktop.
BASH (shopt) Shell Options Explained

Bash Shel Options ( shopt ) Explained

I wasted time WTFM so RTFM

Enable OptionDisable OptionList Enabled OptionsEnabled Options Sample Output
shopt -s <opt>
shopt -u <opt>
echo $BASHOPTS
checkwinsize:cmdhist:complete_fullquote

This table illustrates the behavior of various shopt options in bash. By toggling these options, you can influence how the shell handles things like filename completion, history management, and error handling.

Option Description Disabled Enabled Example
assoc_expand_once Suppress multiple evaluation of associative arrays during arithmetic expressions, variable assignments, and array dereferencing. Normal evaluation Only evaluates once Consider an associative array data with data[key1]=value1 and data[key2]=value2. With this option disabled, result=$((data[key1] + data[key2])) would evaluate data[key1] and data[key2] twice. Enabling assoc_expand_once ensures the array elements are evaluated only once.
autocd Execute directory names as cd commands (interactive shells only). Manual cd required Automatic cd If autocd is on, typing documents in the terminal will change the working directory to "documents" as if you typed cd documents.
cdible_vars Use variable values as directory for cd Error for non-directories Uses variable value Suppose you have a variable project_dir set to /home/user/projects. With cdible_vars enabled, cd $project_dir would change the directory. If cdible_vars is off, this command would result in an error since $project_dir is not a valid directory by itself.
cdspell Correct minor errors in directory spelling Manual correction required Suggests corrections With cdspell on, a typo like teh_wrong_dir might be corrected to the_wrong_dir if that directory exists.
checkhash Verify hashed commands exist before execution Re-attempts execution Skips execution If a command is not found in the hash table (think command cache), bash normally searches the PATH directories. With checkhash enabled, bash would skip this search and throw an error instead.
checkjobs List stopped/running jobs before exiting interactive shell Silent exit Lists jobs When exiting a shell with exit, checkjobs (if enabled) will show a list of background jobs before prompting you to confirm exit.
checkwinsize Update terminal dimensions after each command Potentially outdated dimensions Accurate dimensions This option ensures the shell maintains an accurate representation of your terminal window size for features like cursor positioning.
cmdhist Save multi-line commands as a single history entry Separate entries for each line Single entry for entire command With cmdhist on, a multi-line command like git add .\n git commit -m "Fixed the bug" would be saved as one entry in the history.
complete_fullquote Quote all shell metacharacters in filename completion Metacharacters might be interpreted Protects metacharacters This option helps prevent unintended behavior when completing filenames with special characters like * or $.
direxpand Replace directory names with their expanded forms during completion Shows original directory name Shows expanded path Imagine a directory named proj*ect. With direxpand enabled, completing proj* might show the full path /home/user/projects.
dotglob Include hidden files (starting with .) in filename expansion Hidden files excluded Hidden files included If dotglob is on, ls would list files like .bashrc along with regular files.
expand_aliases Expand aliases when referenced Aliases not expanded Aliases expanded With expand_aliases enabled, using an alias like lg (defined as alias lg="grep") would trigger the grep command.
extglob Enable extended pattern matching features Basic pattern matching More powerful matching Extended patterns allow for complex matching criteria. For instance, shopt -s extglob enables patterns like *.{txt,jpg} to match files with .txt or .jpg extensions.
failglob Errors on failed filename expansion patterns Patterns might silently expand to empty Errors shown for invalid patterns This helps avoid unintended consequences when using patterns that might not match any files.
force_fignore Consider ignored words during filename completion (even if only option) Might complete ignored words Ignores even only completion This option ensures that even if a partially typed word is the only possible completion according to the FIGNORE variable, bash won't suggest it.
globstar Allow '**' pattern to match directories recursively Limited directory matching Recursive matching shopt -s globstar enables ** to match all files and subdirectories within a directory. For example, rm -rf dir/** would recursively delete everything inside the dir directory.
histappend Append history to history file on exit Overwrites history file Maintains history across sessions This ensures your command history is preserved for future use.
histverify Ask for confirmation before using history substitutions Automatic history substitution User verification for substitutions This can prevent accidental execution of unintended commands based on history substitutions.
inherit_errexit Inherit errexit option in command substitutions errexit unset in subshells Maintains errexit behavior This ensures subshells also exit on encountering errors if the main shell has errexit enabled.
interactive_comments Allow comments starting with '#' in interactive shells Comments require manual execution Comments directly disable lines This lets you temporarily disable lines in your shell script by adding # at the beginning.
lithist Save multi-line commands with newlines (if cmdhist is enabled) Uses semicolons to separate lines Preserves newlines in multi-line history entries This ensures better readability of multi-line commands stored in the shell history.
nocaseglob Perform case-insensitive filename expansion Case-sensitive matching Case-insensitive matching With nocaseglob enabled, FILE and File would match the same file.
nocasematch Perform case-insensitive pattern matching Case-sensitive matching Case-insensitive matching Similar to nocaseglob, but applies to broader pattern matching contexts.
nullglob Expand unmatched filename patterns to empty string Patterns might expand to themselves Empty string for no matches This avoids unintended behavior when working with patterns that might not match any files.
promptvars Allow variable expansion and other operations in prompt strings Limited prompt customization Richer prompt customization This enables you to create dynamic prompts that display things like the current directory or username.
shift_verbose Print error message for excessive shift usage Silent errors Informs about invalid shifts This helps identify potential errors in scripts that rely on shifting positional parameters.
sourcepath Use PATH to locate files for the . (source) builtin Might not find files not in PATH Uses PATH for locating source files This ensures the shell can find scripts to source even if they are not in the current directory.
varredir_close Automatically close file descriptors opened using {varname} redirection File descriptors stay open Closes file descriptors This helps prevent resource leaks by ensuring file descriptors opened using syntax like > {output_file} are closed after the command finishes.
xpg_echo Enable backslash-escape sequence interpretation in echo by default Manual escaping required Automatic backslash interpretation With xpg_echo enabled, echo \n would print a newline character because \n is interpreted as a newline escape sequence.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment