bash Cheat Sheet
Function names and special characters
The following are all permitted in function names in addition to [A-Z0-9a-z_]:
- "+", ".", "/", ":", "=", "?", "@", "", "", "^", "_", "{", "}", "~", and even some Unicode symbols
However, for portability with POSIX or other shell implementations it is not recommended.
Shell Options (shopt)
Shell options turn features within bash on and off interactively.
Shell interactivity
cdable_vars- Allowscd HOME(assumes any non-directory is the variable name) (Recommendoff)cdspell- Attempt to fix typos in directory names on the command line (Recommendon)interactive_comments- Command lines that begin with#are comments and should be ignored. (Recommendon)promptvars- Enable variable substitutions in prompt displays (Recommendon)
Execution path
checkhash- Check whether commands found in the hash table exists before executing it. (Recommendon)
Window size
checkwinsize- If set, bash checks the window size after each command and, if necessary, updates the values ofLINESandCOLUMNS. (Recommendon)
History
cmdhist- Save command history to.bash_history(Recommend ison)histappend- When updatingbashhistory, append to the file instead of overwriting it (Recommendon)histreedit- User can edit failed history substitutions whenreadlineis used (Recommendoff)histverify- Allow additional editing of history results prior to execution usingreadline(Recommendoff)lithist- Embed newlines in history entries to ensure commands are stored as one line (Recommendon)
Completions
force_fignore- IgnoreFIGNOREexpansions even when it is the only match (Recommendon)hostcomplete- When user types@on the command line attempt to complete the hostname (Recommendoff)no_empty_cmd_completion- Do not attempt a completion for an empty line (Recommendon)progcomp- Programmable completion is enabled (Recommendon)
Glob behavior
dotglob- Files that start with.are included in pathname expansion (Recommendon)extglob- Extended pattern matching for pathname expansion is enabled (Recommendoff)failglob- Bash will produce an error when a pathname expansion matches no files (Recommendoff)nocaseglob- Pathname expansion is case-insensitive (Recommendoff)nullglob- When a pathname expansion matches no files, return an empty string instead of the pattern (Recommendon)
Shell behavior
extquote- Extended quotes will double-quote$'string'and$"string"within a$parameterexpansion. ( Recommendon. Default ison.)huponexit- If set,bashwill sendSIGHUPto all jobs when an interactive login shell exits. (Recommendoff)execfail- If set, a non-interactive shell will not exit if it cannot execute the file specified as an argument to the exec builtin command. An interactive shell does not exit if exec fails. (Recommendoff)mailwarn- Shows a message about mail on login (Recommendoff)expand_aliases- If set, aliases are expanded as described above under ALIASES. This option is enabled by default for interactive shells. (Recommendon)gnu_errfmt- Use GNU's error format for error messages (Recommendoff)extdebug- Debugging features (Recommendoff)
Language behavior
nocasematch-casestatements are case-insensitive (Recommendoff)sourcepath- When enabled, the.builtin uses the$PATHenvironment to load the file. (Recommendon. Default ison.)shift_verbose-shiftdisplays an error when shifting beyond the arguments available (Recommendon)xpg_echo-echoexpands backslash-escape sequences by default (Recommendoff)compat31- Shell 3.1 compatibility (with=~and quotes) (Recommendoff)
Shell flags
login_shell- Set bybashautomatically if this shell is a login shell (Can not change)restricted_shell- This shell is restricted. (Can not change)
set flags
-a- Export any created or modified variables of subsequent commands-b- Report the status of terminated background jobs immediately, rather than before the next primary prompt. This is effective only when job control is enabled.-e- Exit immediately if a simple command exits with a non-zero status. A trap on ERR, if set, is executed before the shell exits.-f- Disable pathname expansion-h- Remember the location of commands as they are looked up for execution. This is enabled by default.-i- Shell is interactive.-k- All arguments in the form of assignment statements are placed in the environment for a command, not just those that precede the command name.-m- Monitor mode. Job control is enabled.-n- Read commands but do not execute them. This may be used to check a shell script for syntax errors-p- Turn on privileged mode.-t- Exit after reading and executing one command.-u- Treat unset variables as an error when performing parameter expansion. If expansion is attempted on an unset variable, the shell prints an error message, and, if not interactive, exits with a non-zero status.-v- Print shell input lines as they are read.-x- After expanding each simple command, for command, case command, select command, or arithmetic for command, display the expanded value of PS4, followed by the command and its expanded arguments or associated word list.-B- The shell performs brace expansion (see Brace Expansion above). This is on by default.-C- If set, bash does not overwrite an existing file with the >, >&, and <> redirection operators. This may be overridden when creating output files by using the redirection operator >| instead of >.-E- If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment. The ERR trap is normally not inherited in such cases.-H- Enable ! style history substitution. This option is on by default when the shell is interactive.-P- If set, the shell does not follow symbolic links when executing commands such as cd that change the current working directory. It uses the physical directory structure instead. By default, bash follows the logical chain of directories when performing commands which change the current directory.-T- If set, any traps on DEBUG and RETURN are inherited by shell functions, command substitutions, and commands executed in a subshell environment. The DEBUG and RETURN traps are normally not inherited in such cases.--- If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters are set to the args, even if some of them begin with a -.-- Signal the end of options, cause all remaining args to be assigned to the positional parameters. The -x and -v options are turned off. If there are no args, the positional parameters remain unchanged.
The following flags are "sticky" and will remain in parent functions after a function exits:
-a-b-f-m-p-k-C-T
The following flags are scoped to the current function and are unset upon exit to the prior function scope setting:
-e,-E,-u
All settings inherit to called functions.
Option names: -o option-name
allexport- Same as-a.braceexpand- Same as-Bemacs- Use an emacs-style command line editing interface. This is enabled by default when the shell is interactive, unless the shell is started with the--noeditingoption.errtrace- Same as-E.functrace- Same as-T.errexit- Same as-e.hashall- Same as-h.histexpand- Same as-H.history- Enable command history, as described above under HISTORY. This option is on by default in interactive shells.ignoreeof- The effect is as if the shell command ``IGNOREEOF=10'' had been executed (see Shell Variables above).keyword- Same as-k.monitor- Same as-m.noclobber- Same as-C.noexec- Same as-n.noglob- Same as-f.nolog- Currently ignored.notify- Same as-b.nounset- Same as-u.onecmd- Same as-t.physical- Same as-P.pipefail- If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.posix- Change the behavior of bash where the default operation differs from the POSIX standard to match the standard (posix mode).privileged- Same as-p.verboseSame as-v.vi- Use a vi-style command line editing interface.xtrace- Same as-x.
If -o is supplied with no option-name, the values of the current options are printed. If +o is supplied with no
option-name, a series of set commands to recreate the current option settings is displayed on the standard output.
The options are off by default unless otherwise noted. Using + rather than - causes these options to be turned off. The
options can also be specified as arguments to an invocation of the shell. The current set of options may be found in
$-. The return status is always true unless an invalid option is encountered.
Privileged Mode
In this mode, the $ENV and $BASH_ENV files are not processed, shell functions are not inherited from the
environment, and the SHELLOPTS variable, if it appears in the environment, is ignored. If the shell is started with
the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied,
these actions are taken and the effective user id is set to the real user id. If the -p option is supplied at startup,
the effective user id is not reset. Turning this option off causes the effective user and group ids to be set to the
real user and group ids.
Bash Problems
${!variable}and${!variable[@]}have different semantic meanings- No (easy) way to deference an array by another variable name
- The lack of default (empty) arrays leads to errors when doing
"${__emptyArray[@]}"withset -u(and leads to ugly code like"${__emptyArray[@]+"${__emptyArray[@]}"}") readexits 0 on end of file but actually may return a string leading to issues with missing newlines causing problems; use the pattern:local finished=false; while ! $finished; do read -r line || finished=true; ...and then test the value oflinefor non-empty values and handle when$finishedbecomestrue. Source- Problems with
&&or||precedence leads to errors