BASH-BUILTINS(7)

๐Ÿ“ฆ
version 5.3 ยท 4 versions
, in ubuntu resolute, ubuntu stonking

๐ŸŽ€ NAME ๐ŸŽ€

Bestie, welcome to bash-builtins(7) from the Miscellaneous Information Manual โ€” this is the manual for bash built-in commands. If you want the whole bash universe, go see bash(1). It's giving "everything bash can do without even leaving the shell," and honestly? Obsessed. ๐Ÿ’–


โœจ SYNOPSIS โœจ

bash defines the following built-in commands:

:, ., [, alias, bg, bind, break, builtin, case, cd, command, compgen, complete, continue, declare, dirs, disown, echo, enable, eval, exec, exit, export, fc, fg, getopts, hash, help, history, if, jobs, kill, let, local, logout, popd, printf, pushd, pwd, read, readonly, return, set, shift, shopt, source, suspend, test, times, trap, type, typeset, ulimit, umask, unalias, unset, until, wait, while.

๐ŸŒˆ BASH BUILTIN COMMANDS ๐ŸŒˆ

Unless the docs for a builtin say otherwise, every builtin in this section that accepts options preceded by - also accepts -- to say "end of options, bestie". The :, true, false, and test/[ builtins do not accept options, and they do not treat -- specially. The exit, logout, return, break, continue, let, and shift builtins accept and process arguments beginning with - without requiring --. Other builtins that accept arguments but are not specified as accepting options interpret arguments beginning with - as invalid options, and they require -- to prevent that interpretation. ๐Ÿ’…


: ๐Ÿซถ

: [arguments]

No effect. The command does nothing beyond expanding arguments and performing any specified redirections. The return status is zero. That's the whole personality: iconic, silent, zero notes. ๐Ÿ’–


. / source ๐Ÿฆ‹

. [-p path] filename [arguments]
source [-p path] filename [arguments]

The . command (also known as source) reads and executes commands from filename in the current shell environment, and it returns the exit status of the last command executed from filename. It's giving "run this in my current shell, no subprocess drama". โœจ

If filename does not contain a slash, . searches for it. If the -p option is supplied, . treats path as a colon-separated list of directories in which to find filename; otherwise, . uses the entries in PATH to find the directory containing filename. filename does not need to be executable. When bash is not in posix mode, it searches the current directory if filename is not found in PATH, but it does not search the current directory if -p is supplied. If the sourcepath option to the shopt builtin command is turned off, . does not search PATH. ๐Ÿ‘‘

If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. No cap.

If the -T option is enabled, . inherits any trap on DEBUG; if it is not, any DEBUG trap string is saved and restored around the call to ., and . unsets the DEBUG trap while it executes. If -T is not set, and the sourced file changes the DEBUG trap, the new value persists after . completes. The return status is the status of the last command executed from filename (0 if no commands are executed), and non-zero if filename is not found or cannot be read. ๐Ÿ˜ญ


alias ๐ŸŽ€

alias [-p] [name[=value] ...]

With no arguments or with the -p option, alias prints the list of aliases in the form alias name=value on standard output. When arguments are supplied, define an alias for each name whose value is given. A trailing space in value causes the next word to be checked for alias substitution when the alias is expanded during command parsing. For each name in the argument list for which no value is supplied, print the name and value of the alias name. alias returns true unless a name is given (without a corresponding =value) for which no alias has been defined. ๐Ÿ’–


bg ๐Ÿ’…

bg [jobspec ...]

Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell uses its notion of the current job. bg jobspec returns 0 unless run when job control is disabled or, when run with job control enabled, any specified jobspec was not found or was started without job control. ๐ŸŒ€


bind ๐ŸŽน

bind [-m keymap] [-lsvSVX]
bind [-m keymap] [-q function] [-u function] [-r keyseq]
bind [-m keymap] -f filename
bind [-m keymap] -x keyseq[:] shell-command
bind [-m keymap] keyseq:function-name
bind [-m keymap] -p|-P [readline-command]
bind [-m keymap] keyseq:readline-command
bind readline-command-line

Display current readline key and function bindings, bind a key sequence to a readline function or macro or to a shell command, or set a readline variable. Each non-option argument is a key binding or command as it would appear in a readline initialization file such as .inputrc, but each binding or command must be passed as a separate argument; e.g., \C-x\C-r: re-read-init-file. In the following descriptions, output available to be re-read is formatted as commands that would appear in a readline initialization file or that would be supplied as individual arguments to a bind command. Options, if supplied, have the following meanings:

  • -m keymap โ€” Use keymap as the keymap to be affected by the subsequent bindings. Acceptable keymap names are emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. vi is equivalent to vi-command (vi-move is also a synonym); emacs is equivalent to emacs-standard.
  • -l โ€” List the names of all readline functions.
  • -p โ€” Display readline function names and bindings in such a way that they can be used as an argument to a subsequent bind command or in a readline initialization file. If arguments remain after option processing, bind treats them as readline command names and restricts output to those names.
  • -P โ€” List current readline function names and bindings. If arguments remain after option processing, bind treats them as readline command names and restricts output to those names.
  • -s โ€” Display readline key sequences bound to macros and the strings they output in such a way that they can be used as an argument to a subsequent bind command or in a readline initialization file.
  • -S โ€” Display readline key sequences bound to macros and the strings they output.
  • -v โ€” Display readline variable names and values in such a way that they can be used as an argument to a subsequent bind command or in a readline initialization file.
  • -V โ€” List current readline variable names and values.
  • -f filename โ€” Read key bindings from filename.
  • -q function โ€” Display key sequences that invoke the named readline function.
  • -u function โ€” Unbind all key sequences bound to the named readline function.
  • -r keyseq โ€” Remove any current binding for keyseq.
  • -x keyseq[: ]shell-command โ€” Cause shell-command to be executed whenever keyseq is entered. The separator between keyseq and shell-command is either whitespace or a colon optionally followed by whitespace. If the separator is whitespace, shell-command must be enclosed in double quotes and readline expands any of its special backslash-escapes in shell-command before saving it. If the separator is a colon, any enclosing double quotes are optional, and readline does not expand the command string before saving it. Since the entire key binding expression must be a single argument, it should be enclosed in single quotes. When shell-command is executed, the shell sets the READLINE_LINE variable to the contents of the readline line buffer and the READLINE_POINT and READLINE_MARK variables to the current location of the insertion point and the saved insertion point (the mark), respectively. The shell assigns any numeric argument the user supplied to the READLINE_ARGUMENT variable. If there was no argument, that variable is not set. If the executed command changes the value of any of READLINE_LINE, READLINE_POINT, or READLINE_MARK, those new values will be reflected in the editing state.
  • -X โ€” List all key sequences bound to shell commands and the associated commands in a format that can be reused as an argument to a subsequent bind command.

The return value is 0 unless an unrecognized option is supplied or an error occurred.


break ๐Ÿ›‘

break [n]

Exit from within a for, while, until, or select loop. If n is specified, break exits n enclosing loops. n must be โ‰ฅ 1. If n is greater than the number of enclosing loops, all enclosing loops are exited. The return value is 0 unless n is not greater than or equal to 1. ๐Ÿ’ฅ


builtin ๐Ÿงฑ

builtin shell-builtin [arguments]

Execute the specified shell builtin shell-builtin, passing it arguments, and return its exit status. This is useful when defining a function whose name is the same as a shell builtin, retaining the functionality of the builtin within the function. The cd builtin is commonly redefined this way. The return status is false if shell-builtin is not a shell builtin command. ๐Ÿ‘‘


caller ๐Ÿ“ž

caller [expr]

Returns the context of any active subroutine call (a shell function or a script executed with the . or source builtins). ๐Ÿ“ž

Without expr, caller displays the line number and source filename of the current subroutine call. If a non-negative integer is supplied as expr, caller displays the line number, subroutine name, and source file corresponding to that position in the current execution call stack. This extra information may be used, for example, to print a stack trace. The current frame is frame 0.

The return value is 0 unless the shell is not executing a subroutine call or expr does not correspond to a valid position in the call stack.

cd [-L] [-@] [dir]
cd -P [-e] [-@] [dir]

Okay so cd is the "take me somewhere else" queen ๐Ÿ’… It changes the current directory to dir. And if you don't hand it a dir at all? It just uses whatever's chillin' in the HOME shell variable as dir. Self-care, honestly.

Now here's the tea about CDPATH ๐Ÿซ– โ€” if that variable exists and your dir does not start with a slash (/), then cd treats it like a search path: the shell goes through every directory name in CDPATH looking for dir. The alternative directory names in CDPATH are separated by a colon (:). And a null directory name in CDPATH means the same thing as the current directory, i.e. the current directory. Periodt.

The -P option makes cd use the physical directory structure โ€” it resolves symbolic links while it's traversing dir, and before it processes instances of .. in dir. (Peep the -P option on the set builtin too, iykyk.)

The -L option forces cd to follow symbolic links by resolving the link after processing instances of .. in dir. So if .. shows up in dir, cd handles it by removing the immediately previous pathname component from dir, back to a slash or the beginning of dir, and then verifying that the portion of dir it has processed up to that point is still a valid directory name after removing that pathname component. If it's not a valid directory name, cd returns a non-zero status. And if you supply neither -L nor -P? cd acts like you passed -L. It's giving default-to-follow, bestie.

If the -e option comes along with -P, and cd can't successfully figure out the current working directory after a successful directory change, it returns a non-zero status. ๐Ÿ˜ญ

On systems that support it, the -@ option presents the extended attributes associated with a file as a directory. Fancy โœจ

An argument of - gets converted to $OLDPWD before it even attempts the directory change. Nostalgic.

If cd uses a non-empty directory name from CDPATH, or if - is the first argument, and the directory change succeeds, then cd writes the absolute pathname of the new working directory to the standard output. ๐Ÿ“ข

If the directory change is successful, cd sets the value of the PWD environment variable to the new directory name, and sets the OLDPWD environment variable to the value of the current working directory before the change. Glow up documented.

The return value is true if the directory was successfully changed; false otherwise.


command [-pVv] command [arg ...]

The command builtin runs command with args, and it does this while suppressing the normal shell function lookup for command. Only builtin commands, or commands found in the PATH named command, get executed. No sneaky functions invited to the party ๐Ÿšซ

If the -p option is supplied, the search for command is performed using a default value for PATH that is guaranteed to find all of the standard utilities. Trust issues, but make it productive.

If either the -V or -v option is supplied, command prints a description of command. The -v option displays a single word indicating the command or filename used to invoke command; the -V option produces a more verbose description. One is the sparknotes, one is the full essay ๐ŸŽ€

If the -V or -v option is supplied, the exit status is zero if command was found, and non-zero if not. If neither option is supplied and an error occurred, or command can't be found, the exit status is 127. Otherwise, the exit status of the command builtin is the exit status of command. Number delivery, exactly as promised ๐Ÿ’€


compgen [-V varname] [option] [word]

compgen generates possible completion matches for word according to the options โ€” and those options may be any option accepted by the complete builtin, with the exceptions of -p, -r, -D, -E, and -I. Then it writes the matches to the standard output. It's literally the completion match factory ๐Ÿญ

If the -V option is supplied, compgen stores the generated completions into the indexed array variable varname instead of writing them to the standard output. Stashing instead of spilling.

When using the -F or -C options, the various shell variables set by the programmable completion facilities, while available, will not have useful values. Heads up, bestie โ€” they're there but they're not serving ๐Ÿ™ˆ

The matches will be generated in the same way as if the programmable completion code had generated them directly from a completion specification with the same flags. And if word is specified, only those completions matching word will be displayed or stored. Filtered, gorgeously.

The return value is true unless an invalid option is supplied, or no matches were generated.


complete [-abcdefgjksuv] [-o comp-option] [-DEI] [-A action]
         [-G globpat] [-W wordlist] [-F function] [-C command]
         [-X filterpat] [-P prefix] [-S suffix] name [name ...]
complete -pr [-DEI] [name ...]

Specify how arguments to each name should be completed. This is you, telling the shell how to finish your sentences. Iconic behaviour ๐Ÿ‘‘

If the -p option is supplied, or if no options or names are supplied at all, complete prints existing completion specifications in a way that allows them to be reused as input. Copy-paste-ready, we love a recyclable format โ™ป๏ธ

The -r option removes a completion specification for each name, or โ€” if no names are supplied โ€” all completion specifications. Deletion era.

The -D option indicates that the other supplied options and actions should apply to the command completion; that is, completion attempted on a command for which no completion has previously been defined.

The -E option indicates that other supplied options and actions should apply to command completion; that is, completion attempted on a blank line.

The -I option indicates that other supplied options and actions should apply to completion on the initial non-assignment word on the line, or after a command delimiter such as ; or |, which is usually command name completion.

If multiple options are supplied, the -D option takes precedence over -E, and both take precedence over -I. If any of -D, -E, or -I are supplied, any other name arguments are ignored; these completions only apply to the case specified by the option. Sorry to those names, they're not the main character today ๐Ÿ˜ญ

The process of applying these completion specifications when attempting word completion is described in bash(1). Go read the lore.

Other options, if specified, have the following meanings. The arguments to the -G, -W, and -X options (and, if necessary, the -P and -S options) should be quoted to protect them from expansion before the complete builtin is invoked. Quote them, protect them, wrap them in a little blanket ๐Ÿงš

  • -o comp-option โ€” this lil guy controls โœจhowโœจ the compspec behaves way beyond just spitting out completions. comp-option can be any one of these besties:
    • bashdefault โ€” if the compspec gives you zero matches, go ahead and do the rest of the default bash completions. no hard feelings ๐Ÿ’–
    • default โ€” if the compspec generates no matches, fall back to readline's default filename completion.
    • dirnames โ€” if the compspec generates no matches, do directory name completion instead.
    • filenames โ€” tell readline that the compspec is generating filenames, so it can do all its filename-specific glow-up processing (like adding a slash to directory names, quoting special characters, or suppressing trailing spaces). this one's meant to be used with shell functions, periodt.
    • fullquote โ€” tell readline to quote all the completed words, even if they're not filenames.
    • noquote โ€” tell readline not to quote the completed words if they're filenames (fun fact: quoting filenames is the default).
    • nosort โ€” tell readline not to sort the list of possible completions alphabetically. chaos mode, respectfully ๐Ÿฆ‹
    • nospace โ€” tell readline not to append a space (which is the default) to words completed at the end of the line.
    • plusdirs โ€” after generating any matches defined by the compspec, also attempt directory name completion and add any matches to the results of the other actions. teamwork makes the dream work ๐Ÿ’…
  • -A action โ€” action can be any one of the following, and it generates a list of possible completions:
    • alias โ€” alias names. can also be written as -a.
    • arrayvar โ€” array variable names.
    • binding โ€” readline key binding names.
    • builtin โ€” names of shell builtin commands. can also be written as -b.
    • command โ€” command names. can also be written as -c.
    • directory โ€” directory names. can also be written as -d.
    • disabled โ€” names of disabled shell builtins.
    • enabled โ€” names of enabled shell builtins.
    • export โ€” names of exported shell variables. can also be written as -e.
    • file โ€” file and directory names, similar to readline's filename completion. can also be written as -f.
    • function โ€” names of shell functions.
    • group โ€” group names. can also be written as -g.
    • helptopic โ€” help topics as accepted by the help builtin.
    • hostname โ€” hostnames, as taken from the file specified by the HOSTFILE shell variable.
    • job โ€” job names, if job control is active. can also be written as -j.
    • keyword โ€” shell reserved words. can also be written as -k.
    • running โ€” names of running jobs, if job control is active.
    • service โ€” service names. can also be written as -s.
    • setopt โ€” valid arguments for the -o option to the set builtin.
    • shopt โ€” shell option names as accepted by the shopt builtin.
    • signal โ€” signal names.
    • stopped โ€” names of stopped jobs, if job control is active.
    • user โ€” user names. can also be written as -u.
    • variable โ€” names of all shell variables. can also be written as -v.
  • -C command โ€” command gets executed in a subshell environment, and its output is used as the possible completions. arguments are passed the same way as with the -F option.
  • -F function โ€” the shell function function runs in the current shell environment. when the function executes, the first argument ($1) is the name of the command whose arguments are being completed, the second argument ($2) is the word being completed, and the third argument ($3) is the word preceding the word being completed on the current command line. when function finishes, programmable completion pulls the possible completions from the value of the COMPREPLY array variable. iconic behavior fr fr ๐Ÿ‘‘
  • -G globpat โ€” expand the pathname expansion pattern globpat to generate the possible completions.
  • -P prefix โ€” add prefix to the beginning of each possible completion, after all the other options have been applied.
  • -S suffix โ€” append suffix to each possible completion, after all the other options have been applied.
  • -W wordlist โ€” split the wordlist using the characters in the IFS special variable as delimiters, then expand each resulting word. shell quoting is honored inside wordlist, so there's a whole mechanism for words to contain shell metacharacters or characters that live in the value of IFS. the possible completions are the members of the resulting list that match a prefix of the word being completed.
  • -X filterpat โ€” filterpat is a pattern, same kind you'd use for pathname expansion. it gets applied to the list of possible completions generated by the preceding options and arguments, and every completion matching filterpat gets removed from the list. a leading ! in filterpat negates the pattern โ€” in that case, any completion not matching filterpat is the one that gets removed. ๐Ÿ’€

The return value is true unless an invalid option is supplied, unless an option other than -p, -r, -D, -E, or -I is supplied without a name argument, unless someone tries to remove a completion specification for a name that has no specification, or unless an error occurs while adding a completion specification.


โœจ compopt โœจ

compopt [-o option] [-DEI] [+o option] [name]

Modify completion options for each name according to the options, or for the currently-executing completion if no names are supplied. if you supply no options at all, it displays the completion options for each name or for the current completion. the possible values of option are exactly the ones that are valid for the complete builtin up above, bestie ๐Ÿ’–

  • -D โ€” says the other supplied options should apply to the command completion.
  • -E โ€” says the other supplied options should apply to command completion.
  • -I โ€” says the other supplied options should apply to completion on the initial word on the line.

these get determined the same way as in the complete builtin, no cap.

If multiple options are supplied, -D takes precedence over -E, and both of them take precedence over -I. hierarchy, we love to see it ๐ŸŽ€

The return value is true unless an invalid option is supplied, unless someone tries to modify the options for a name that has no completion specification, or unless an output error occurs.


โœจ continue โœจ

continue [n]

continue resumes the next iteration of the enclosing for, while, until, or select loop. if n is specified, bash resumes the nth enclosing loop. n must be โ‰ฅ 1. if n is greater than the number of enclosing loops, the shell resumes the last enclosing loop (the loop, babe, the one we're in). ๐ŸŒธ

The return value is 0 unless n is not greater than or equal to 1.


โœจ declare โœจ

declare [-aAfFgiIlnrtux] [-p] [name[=value] ...]

โœจ typeset โœจ

typeset [-aAfFgiIlnrtux] [-p] [name[=value] ...]

Declare variables and/or give them attributes. if no names are given, then it displays the values of variables or functions. the -p option displays the attributes and values of each name. when -p is used with name arguments, any additional options other than -f and -F get straight-up ignored. rude but true ๐Ÿ’…

When -p is supplied without name arguments, declare displays the attributes and values of all variables having the attributes specified by the additional options. if no other options are supplied alongside -p, declare displays the attributes and values of all shell variables. the -f option restricts the display to shell functions.

The -F option inhibits the display of function definitions โ€” only the function name and attributes get printed. if the extdebug shell option is enabled using shopt, the source file name and line number where each name is defined get displayed too. the -F option implies -f. receipts included ๐Ÿงš

The -g option forces variables to be created or modified at the global scope, even when declare is executed inside a shell function. it's ignored when declare isn't executed in a shell function.

The -I option causes local variables to inherit the attributes (except the nameref attribute) and value of any existing variable with the same name at a surrounding scope. if there's no existing variable, the local variable starts out initially unset.

The following options can be used to restrict output to variables with the specified attribute, or to give variables attributes:

  • -a โ€” each name is an indexed array variable (see Arrays in bash(1)). ๐Ÿ’…
  • -A โ€” each name is an associative array variable (see Arrays in bash(1)).
  • -f โ€” each name refers to a shell function.
  • -i โ€” the variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION in bash(1)) is performed when the variable is assigned a value.
  • -l โ€” when the variable is assigned a value, all upper-case characters are converted to lower-case. The upper-case attribute is disabled.
  • -n โ€” give each name the nameref attribute, making it a name reference to another variable. That other variable is defined by the value of name. All references, assignments, and attribute modifications to name, except those using or changing the -n attribute itself, are performed on the variable referenced by name's value. The nameref attribute cannot be applied to array variables.
  • -r โ€” make names readonly. These names cannot then be assigned values by subsequent assignment statements or unset. ๐Ÿ”’
  • -t โ€” give each name the trace attribute. Traced functions inherit the DEBUG and RETURN traps from the calling shell. The trace attribute has no special meaning for variables.
  • -u โ€” when the variable is assigned a value, all lower-case characters are converted to upper-case. The lower-case attribute is disabled.
  • -x โ€” mark each name for export to subsequent commands via the environment.

Using + instead of - turns off the specified attribute instead, with the exceptions that +a and +A may not be used to destroy array variables and +r will not remove the readonly attribute.

When used in a function, declare and typeset make each name local, as with the local command, unless the -g option is supplied. If a variable name is followed by =value, the value of the variable is set to value. When using -a or -A and the compound assignment syntax to create array variables, additional attributes do not take effect until subsequent assignments. ๐Ÿ‘‘

The return value is 0 unless an invalid option is encountered, an attempt is made to define a function using, an attempt is made to assign a value to a readonly variable, an attempt is made to assign a value to an array variable without using the compound assignment syntax (see Arrays in bash(1)), one of the names is not a valid shell variable name, an attempt is made to turn off readonly status for a readonly variable, an attempt is made to turn off array status for an array variable, or an attempt is made to display a non-existent function with -f.


๐ŸŒ€ dirs [-clpv] [+n] [-n]

No options? Then it just shows you the list of directories it's currently remembering, bestie. Default display is a single line, directory names separated by spaces. Directories get added to that list by the pushd command, and popd takes entries back out. And the current directory is always the first directory in the stack. periodt.

Options, if supplied, have the following meanings:

  • -c โ€” clears the directory stack by deleting all of the entries. ๐Ÿงน
  • -l โ€” produces a listing using full pathnames; the default listing format uses a tilde to denote the home directory.
  • -p โ€” print the directory stack with one entry per line.
  • -v โ€” print the directory stack with one entry per line, prefixing each entry with its index in the stack.
  • +n โ€” displays the *n*th entry counting from the left of the list shown by dirs when invoked without options, starting with zero.
  • -n โ€” displays the *n*th entry counting from the right of the list shown by dirs when invoked without options, starting with zero.

The return value is 0 unless an invalid option is supplied or n indexes beyond the end of the directory stack. ๐Ÿ˜ญ


๐Ÿซถ disown [-ar] [-h] [id ...]

No options โ†’ it removes each id from the table of active jobs. Each id may be a job specification jobspec or a process ID pid; if id is a pid, disown uses the job containing pid as jobspec.

If the -h option is supplied, disown does not remove the jobs corresponding to each id from the jobs table, but rather marks them so the shell does not send SIGHUP to the job if the shell receives a SIGHUP. โœจ (yes this is the "pls don't die when I close the terminal" flag, iykyk)

If no id is supplied, the -a option means to remove or mark all jobs; the -r option without an id argument removes or marks running jobs. If no id is supplied, and neither the -a nor the -r option is supplied, disown removes or marks the current job.

The return value is 0 unless an id does not specify a valid job.


๐ŸŽ€ echo [-neE] [arg ...]

Outputs the args, separated by spaces, followed by a newline. ๐ŸŒˆ The return status is 0 unless a write error occurs. If -n is specified, the trailing newline is not printed. (yes, echo -n is that girl)

If the -e option is given, echo interprets the following backslash-escaped characters. The -E option disables interpretation of these escape characters, even on systems where they are interpreted by default. The xpg_echo shell option determines whether or not echo interprets any options and expands these escape characters. echo does not interpret -- to mean the end of options. ๐Ÿ’€

echo interprets the following escape sequences:

  • \a โ€” alert (bell)
  • \b โ€” backspace
  • \c โ€” suppress further output
  • \e
  • \E โ€” an escape character
  • \f โ€” form feed
  • \n โ€” new line
  • \r โ€” carriage return
  • \t โ€” horizontal tab
  • \v โ€” vertical tab
  • \\ โ€” backslash
  • \0nnn โ€” the eight-bit character whose value is the octal value nnn (zero to three octal digits).
  • \xHH โ€” the eight-bit character whose value is the hexadecimal value HH (one or two hex digits).
  • \uHHHH โ€” the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits).
  • \UHHHHHHHH โ€” the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits).

echo writes any unrecognized backslash-escaped characters unchanged.


๐Ÿ’œ enable [-a] [-dnps] [-f filename] [name ...]

Enable and disable builtin shell commands. ๐ŸŽ›๏ธ Disabling a builtin allows an executable file which has the same name as a shell builtin to be executed without specifying a full pathname, even though the shell normally searches for builtins before files.

If -n is supplied, each name is disabled; otherwise, names are enabled. For example, to use the test binary found using PATH instead of the shell builtin version, run

If no name arguments are supplied, or if the -p option is supplied, print a list of shell builtins. With no other option arguments, the list consists of all enabled shell builtins. If -n is supplied, print only disabled builtins. If -a is supplied, the list printed includes all builtins, with an indication of whether or not each is enabled. The -s option means to restrict the output to the POSIX special builtins. โญ

The -f option means to load the new builtin command name from shared object filename, on systems that support dynamic loading. If filename does not contain a slash, Bash will use the value of the BASH_LOADABLES_PATH variable as a colon-separated list of directories in which to search for filename. The default for BASH_LOADABLES_PATH is system-dependent, and may include to force a search of the current directory. The -d option will delete a builtin previously loaded with -f. If -s is used with -f, the new builtin becomes a POSIX special builtin. ๐Ÿ”ฅ

If no options are supplied and a name is not a shell builtin, enable will attempt to load name from a shared object named name, as if the command were

The return value is 0 unless a name is not a shell builtin or there is an error loading a new builtin from a shared object.


๐Ÿฆ‹ eval [arg ...]

Concatenate the args together into a single command, separating them with spaces. Bash then reads and executes this command, and returns its exit status as the return status of eval. If there are no args, or only null arguments, eval returns 0. (the "run this string like it's real" command, no cap)


๐Ÿ‘‘ exec [-cl] [-a name] [command [arguments]]

If command is specified, it replaces the shell without creating a new process. command cannot be a shell builtin or function. The arguments become the arguments to command. If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command. This is what login(1) does. The -c option causes command to be executed with an empty environment. If -a is supplied, the shell passes name as the zeroth argument to the executed command.

If command cannot be executed for some reason, a non-interactive shell exits, unless the execfail shell option is enabled. In that case, it returns a non-zero status. An interactive shell returns a non-zero status if the file cannot be executed. A subshell exits unconditionally if exec fails. ๐Ÿ˜ญ

If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1.


๐ŸŒธ exit [n]

Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. Any trap on EXIT is executed before the shell terminates. ๐Ÿšชโœจ


๐Ÿ“ export [-fn] [name[=value]] ...

๐Ÿ“ export -p [-f]

The supplied names are marked for automatic export to the environment of subsequently executed commands. If the -f option is given, the names refer to functions.

The -n option unexports, aka it removes the export attribute, from each name. If you give it no names at all, or you only hand it -p, export just dumps a list of the names of every exported variable onto standard output. And if you use -p and -f together? You get the exported functions instead. ๐ŸŽ€ The -p option prints its output in a form that may be reused as input, which is lowkey the most useful thing ever.

export also lets you set a variable's value at the exact same time you export (or unexport) it โ€” just follow the variable name with =value. That sets the value of the variable to value while it's busy modifying the export attribute. โœจ

export returns an exit status of 0 unless:

  • an invalid option is encountered,
  • one of the names isn't a valid shell variable name, or
  • -f is supplied with a name that isn't a function.

๐Ÿซถ false

Does nothing. Returns a non-zero status. That's the whole job. It's giving iconically unhelpful and we respect it. ๐Ÿ’…


๐ŸŒธ fc

fc [-e ename] [-lnr] [first] [last]
fc -s [pat=rep] [cmd]

The first form selects a range of commands from first to last out of the history list, then displays them or edits them and re-executes them. โœจ first and last can be a string (which locates the last command beginning with that string) or a number (an index into the history list, where a negative number is used as an offset from the current command number).

When listing, a first or last of 0 is equivalent to -1, and -0 is equivalent to the current command (usually the fc command itself, bestie ๐Ÿ˜ญ); otherwise 0 is equivalent to -1 and -0 is invalid. If last isn't specified, it's set to the current command for listing (so that it prints the last 10 commands) and to first otherwise. If first isn't specified, it's set to the previous command for editing and -16 for listing.

If the -l option is supplied, the commands are listed on the standard output. The -n option suppresses the command numbers when listing. The -r option reverses the order of the commands. ๐Ÿ”„

Otherwise, fc invokes the editor named by ename on a file containing those commands. If ename isn't supplied, fc uses the value of the FCEDIT variable, and the value of EDITOR if FCEDIT isn't set. If neither variable is set, fc uses When editing is complete, fc reads the file containing the edited commands and echoes and executes them.

ngl bestie, the text I've got here looks chopped mid-sentence ๐Ÿ™ˆ I am not about to invent a value for you, so you're getting exactly what it says. Same energy as a group chat message that got sent too early.

In the second form, fc re-executes command after replacing each instance of pat with rep. Command is interpreted the same as first above.

A useful alias to use with fc is so that typing runs the last command beginning with and typing re-executes the last command.

and yeah, that one's chopped too ๐Ÿ˜ญ the alias name and the letters you'd type are missing from my copy. No cap, I'm not making them up. ๐Ÿซถ

If the first form is used, the return value is zero unless an invalid option is encountered or first or last specify history lines out of range. When editing and re-executing a file of commands, the return value is the value of the last command executed, or failure if an error occurs with the temporary file. If the second form is used, the return status is that of the re-executed command โ€” unless cmd doesn't specify a valid history entry, in which case fc returns a non-zero status. ๐Ÿ’€


๐Ÿ‘‘ fg

fg [jobspec]

Resume jobspec in the foreground, and make it the current job. โญ If jobspec isn't present, fg uses the shell's notion of the current job. The return value is that of the command placed into the foreground โ€” or failure if it's run when job control is disabled, or (when run with job control enabled) if jobspec doesn't specify a valid job, or if jobspec specifies a job that was started without job control.


๐Ÿงš getopts

getopts optstring name [arg ...]

getopts is the builtin that shell scripts and functions use to parse positional parameters and pull out options and their arguments. optstring contains the option characters to be recognized; if a character is followed by a colon, that option is expected to have an argument, and that argument should be separated from it by white space. The colon and question mark characters may not be used as option characters. ๐Ÿšซ

Every time it's invoked, getopts places the next option in the shell variable name, initializing name if it doesn't exist, and shoves the index of the next argument to be processed into the variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the variable OPTARG. โœจ

heads up bestie โ€” the shell does not reset OPTIND automatically. You have to manually reset it between multiple calls to getopts within the same shell invocation if you want to use a new set of parameters. Don't get caught out. ๐Ÿ™ˆ

When it reaches the end of options, getopts exits with a return value greater than zero. OPTIND is set to the index of the first non-option argument, and name is set to ?.

getopts normally parses the positional parameters, but if more arguments are supplied as arg values, getopts parses those instead.

getopts can report errors in two ways. If the first character of optstring is a colon, getopts uses silent error reporting. In normal operation, getopts prints diagnostic messages when it encounters invalid options or missing option arguments. If the variable OPTERR is set to 0, getopts doesn't display any error messages, even if the first character of optstring is not a colon.

If getopts detects an invalid option, it places ? into name and, if not silent, prints an error message and unsets OPTARG. If getopts is silent, it assigns the option character found to OPTARG and doesn't print a diagnostic message. ๐Ÿคซ

If a required argument isn't found, and getopts isn't silent, it sets the value of name to a question mark (?), unsets OPTARG, and prints a diagnostic message. If getopts is silent, it sets the value of name to a colon (:) and sets OPTARG to the option character found.

getopts returns true if an option, specified or unspecified, is found. It returns false if the end of options is encountered or an error occurs. โœ…


๐ŸŒˆ hash

hash [-lr] [-p filename] [-dt] [name]

Every time hash is invoked, it remembers the full pathname of the command name as determined by searching the directories in $PATH. Any previously-remembered pathname associated with name is discarded. If the -p option is supplied, hash uses filename as the full pathname of the command.

The -r option causes the shell to forget all remembered locations. Assigning to the PATH variable also clears all hashed filenames. The -d option causes the shell to forget the remembered location of each name.

If the -t option is supplied, hash prints the full pathname corresponding to each name. If multiple name arguments are supplied with -t, hash prints the name before the corresponding hashed full pathname. The -l option displays output in a format that may be reused as input. ๐Ÿ’–

If no arguments are given, or if only -l is supplied, hash prints information about remembered commands. The -t, -d, and -p options (the ones that act on the name arguments) are mutually exclusive โ€” only one will be active. If you supply more than one, here's the priority order, no cap:

  1. -t has higher priority than -p
  2. and both of those have higher priority than -d

The return status is zero unless a name isn't found or an invalid option is supplied.


๐ŸŽ€ help

help [-dms] [pattern]

Display helpful information about builtin commands. โœจ If pattern is specified, help gives detailed help on all commands matching pattern as described below; otherwise it displays a list of all the builtins and shell compound commands.

Options, if supplied, have the following meanings:

  • -d โ€” Display a short description of each pattern
  • -m โ€” Display the description of each pattern in a manpage-like format
  • -s โ€” Display only a short usage synopsis for each pattern

If pattern contains pattern matching characters (see Pattern Matching above), it's treated as a shell pattern and help prints the description of each help topic matching pattern. ๐Ÿฆ‹

If not, and pattern exactly matches the name of a help topic, help prints the description associated with that topic. Otherwise, help performs prefix matching and prints the descriptions of all matching help topics.

The return status is 0 unless no command matches pattern. ๐Ÿ˜ญ


๐Ÿ’œ history

history [n]
history -c
history -d offset
history -d start-end
history -anrw [filename]
history -p arg [arg ...]
history -s arg [arg ...]

With no options, display the command history list with numbers. ๐Ÿ“œ Entries prefixed with a * have been modified. An argument of n lists only the last n entries. If the shell variable HISTTIMEFORMAT is set and not null, it's used as a format string for strftime(3) to display the time stamp associated with each displayed history entry. If history uses HISTTIMEFORMAT, it does not print an intervening space between the formatted time stamp and the history entry. โฐ

If filename is supplied, history uses it as the name of the history file; if not, it uses the value of HISTFILE. If filename isn't supplied and HISTFILE is unset or null, the -a, -n, -r, and -w options have no effect. ๐Ÿ’€

so bestie, if you hand history some options, here's the whole tea โ˜•๏ธ

  • -c โ€” nukes the entire history list, deleting all the entries. You can pair it with the other options if what you're actually trying to do is replace the history list. It's giving factory reset ๐Ÿ’€
  • -d offset โ€” deletes the history entry chillin' at position offset. If offset is negative, it gets interpreted as relative to one greater than the last history position, so negative indices count back from the end of the history, and an index of -1 refers to the current history -d command itself. sneaky little thing ๐Ÿ‘€
  • -d start-end โ€” deletes the whole range of history entries between positions start and end, inclusive. Positive and negative values for start and end are interpreted exactly like we just said above.
  • -a โ€” appends the history lines to the history file. Which lines? The ones entered since the beginning of the current bash session that have not already been appended to the history file. no dupes here โœจ
  • -n โ€” reads the history lines not already read from the history file and adds them to the current history list. Those are the lines appended to the history file since the beginning of the current bash session.
  • -r โ€” reads the history file and appends its contents to the current history list.
  • -w โ€” writes the current history list to the history file, overwriting the history file. gone-gone, no takebacks ๐Ÿซฃ
  • -p โ€” performs history substitution on the following args and displays the result on the standard output, without storing the results in the history list. Each arg must be quoted to disable normal history expansion. iykyk ๐Ÿ”ฅ
  • -s โ€” stores the args in the history list as a single entry. The last command in the history list is removed before adding the args. cute little swap ๐ŸŽ€

If the HISTTIMEFORMAT variable is set, history writes the time stamp information associated with each history entry to the history file, marked with the history comment character as described above. And when the history file is read, lines beginning with the history comment character followed immediately by a digit are interpreted as timestamps for the following history entry. โฐ iconic behaviour honestly

The return value is 0 unless an invalid option is encountered, an error occurs while reading or writing the history file, an invalid offset or range is supplied as an argument to -d, or the history expansion supplied as an argument to -p fails.


๐Ÿ’ผ jobs โ€” the "what's running rn" report

jobs [-lnprs] [ jobspec ... ]
jobs -x command [ args ... ]

The first form lists the active jobs. The options mean this:

  • -l โ€” list process IDs in addition to the normal information. more numbers, more power ๐Ÿ‘‘
  • -n โ€” display information only about jobs that have changed status since the user was last notified of their status.
  • -p โ€” list only the process ID of the job's process group leader.
  • -r โ€” display only running jobs.
  • -s โ€” display only stopped jobs.

If jobspec is supplied, jobs restricts output to information about that job. The return status is 0 unless an invalid option is encountered or an invalid jobspec is supplied.

If the -x option is supplied, jobs replaces any jobspec found in command or args with the corresponding process group ID, and executes command, passing it args, returning its exit status. โœจ


๐Ÿ’€ kill โ€” send signals, be dramatic about it

kill [-s sigspec | -n signum | -sigspec] id [ ... ]
kill -l|-L [sigspec | exit_status]

Send the signal specified by sigspec or signum to the processes named by each id. Each id may be a job specification jobspec or a process ID pid. sigspec is either a case-insensitive signal name such as SIGKILL (with or without the SIG prefix) or a signal number; signum is a signal number. And if sigspec is not supplied at all? Then kill sends SIGTERM. the classic ๐Ÿ’…

The -l option lists the signal names. If any arguments are supplied when -l is given, kill lists the names of the signals corresponding to the arguments, and the return status is 0. The exit_status argument to -l is a number specifying either a signal number or the exit status of a process terminated by a signal; if it is supplied, kill prints the name of the signal that caused the process to terminate. And heads up โ€” kill assumes that process exit statuses are greater than 128; anything less than that is a signal number. The -L option is equivalent to -l. twins fr fr ๐Ÿซถ

kill returns true if at least one signal was successfully sent, or false if an error occurs or an invalid option is encountered.


๐Ÿงฎ let โ€” math but make it builtin

let arg [arg ...]

Each arg is evaluated as an arithmetic expression (see ARITHMETIC EVALUATION in bash(1)). If the last arg evaluates to 0, let returns 1; otherwise let returns 0. yes bestie, zero means failure here, don't fight it ๐Ÿ˜ญ


๐Ÿ  local โ€” keep it in the family (function)

local [option] [name[=value] ... | - ]

For each argument, create a local variable named name and assign it value. The option can be any of the options accepted by declare. When local is used within a function, it causes the variable name to have a visible scope restricted to that function and its children. And it is an error to use local when not within a function. no cap ๐Ÿšซ

If name is -, it makes the set of shell options local to the function in which local is invoked: any shell options changed using the set builtin inside the function after the call to local are restored to their original values when the function returns. The restore is performed as if a series of set commands were executed to restore the values that were in place before the function. time travel, but legal ๐Ÿฆ‹

With no operands, local writes a list of local variables to the standard output.

The return status is 0 unless local is used outside a function, an invalid name is supplied, or name is a readonly variable.


๐Ÿšช logout โ€” bye bestie

logout [n]

Exit a login shell, returning a status of n to the shell's parent. short, sweet, iconic ๐ŸŒธ


๐Ÿ“š mapfile / readarray โ€” slurp lines into an array

mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C
callback] [-c quantum] [array]
readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C
callback] [-c quantum] [array]

Read lines from the standard input, or from file descriptor fd if the -u option is supplied, into the indexed array variable array. The variable MAPFILE is the default array. Options, if supplied, have the following meanings:

  • -d โ€” use the first character of delim to terminate each input line, rather than newline. And if delim is the empty string, mapfile will terminate a line when it reads a NUL character.
  • -n โ€” copy at most count lines. If count is 0, copy all lines.
  • -O โ€” begin assigning to array at index origin. The default index is 0.
  • -s โ€” discard the first count lines read.
  • -t โ€” remove a trailing delim (default newline) from each line read.
  • -u โ€” read lines from file descriptor fd instead of the standard input.
  • -C โ€” evaluate callback each time quantum lines are read. The -c option specifies quantum.
  • -c โ€” specify the number of lines read between each call to callback.

If -C is specified without -c, the default quantum is 5000. When callback is evaluated, it is supplied the index of the next array element to be assigned and the line to be assigned to that element as additional arguments. And callback is evaluated after the line is read but before the array element is assigned. timing is everything, bestie โญ

If not supplied with an explicit origin, mapfile will clear array before assigning to it. ๐Ÿ™ˆ

mapfile returns zero unless an invalid option or option argument is supplied, array is invalid or unassignable, or if array is not an indexed array.


๐ŸŽ€ popd โ€” pop that directory stack

popd [-n] [+n] [-n]

Remove entries from the directory stack. The elements are numbered from 0 starting at the first directory listed by dirs, so popd is equivalent to With no arguments, popd removes the top directory from the stack, and changes to the new top directory. (yes, the sentence really does just do that in the original, we're all living with it ๐Ÿ’€)

Arguments, if supplied, have the following meanings:

  • -n โ€” suppress the normal change of directory when removing directories from the stack; only manipulate the stack.
  • +n โ€” remove the *n*th entry counting from the left of the list shown by dirs, starting with zero, from the stack. For example: removes the first directory, the second.
  • -n โ€” remove the *n*th entry counting from the right of the list shown by dirs, starting with zero. For example: removes the last directory, the next to last.

If the top element of the directory stack is modified, and the -n option was not supplied, popd uses the cd builtin to change to the directory at the top of the stack. If the cd fails, popd returns a non-zero value. ๐Ÿ˜ฌ

Otherwise, popd returns false if an invalid option is supplied, the directory stack is empty, or n specifies a non-existent directory stack entry.

If the popd command is successful, bash runs dirs to show the final contents of the directory stack, and the return status is 0. slay ๐Ÿ’…


๐Ÿ–จ๏ธ printf โ€” formatted output, but as a builtin

printf [-v var] format [arguments]

Write the formatted arguments to the standard output under the control of the format. The -v option assigns the output to the variable var rather than printing it to the standard output. printing? no. variable? yes. main character energy ๐Ÿ’œ

So the format is a character string, and it's lowkey carrying three types of objects: plain characters, which are simply copied to standard output, character escape sequences, which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive argument. On top of the standard printf(3) format characters cCsSndiouxXeEfFgGaA, printf also interprets these extra format specifiers, bestie:

  • %b โ€” makes printf expand backslash escape sequences in the corresponding argument in the same way as echo -e. ๐Ÿ’…
  • %q โ€” makes printf output the corresponding argument in a format that can be reused as shell input. %q and %Q use the $ quoting style if any characters in the argument string require it, and backslash quoting otherwise. If the format string uses the printf alternate form, these two formats quote the argument string using single quotes.
  • %Q โ€” like %q, but applies any supplied precision to the argument before quoting it.
  • %(datefmt)T โ€” makes printf output the date-time string resulting from using datefmt as a format string for strftime(3). The corresponding argument is an integer representing the number of seconds since the epoch. This format specifier recognizes two special argument values: -1 represents the current time, and -2 represents the time the shell was invoked. If no argument is specified, conversion behaves as if -1 had been supplied. This is an exception to the usual printf behavior. ๐Ÿ•ฐ๏ธ

The %b, %q, and %T format specifiers all use the field width and precision arguments from the format specification and write that many bytes from (or use that wide a field for) the expanded argument, which usually contains more characters than the original. No cap.

The %n format specifier accepts a corresponding argument that is treated as a shell variable name.

The %s and %c format specifiers accept an l (long) modifier, which forces them to convert the argument string to a wide-character string and apply any supplied field width and precision in terms of characters, not bytes. The %S and %C format specifiers are equivalent to %ls and %lc, respectively. Slay.

Arguments to non-string format specifiers are treated as C constants, except that a leading plus or minus sign is allowed, and if the leading character is a single or double quote, the value is the numeric value of the following character, using the current locale.

The format is reused as necessary to consume all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied. The return value is zero on success, non-zero if an invalid option is supplied or a write or assignment error occurs. Periodt.


pushd ๐Ÿ’…

pushd [-n] [+n] [-n]
pushd [-n] [dir]

Add a directory to the top of the directory stack, or rotate the stack, making the new top of the stack the current working directory. With no arguments, pushd exchanges the top two elements of the directory stack. Arguments, if supplied, have the following meanings:

  • -n โ€” Suppress the normal change of directory when rotating or adding directories to the stack, only manipulate the stack.
  • +n โ€” Rotate the stack so that the nth directory (counting from the left of the list shown by dirs, starting with zero) is at the top.
  • -n โ€” Rotates the stack so that the nth directory (counting from the right of the list shown by dirs, starting with zero) is at the top.
  • dir โ€” Adds dir to the directory stack at the top.

After the stack has been modified, if the -n option was not supplied, pushd uses the cd builtin to change to the directory at the top of the stack. If the cd fails, pushd returns a non-zero value.

Otherwise, if no arguments are supplied, pushd returns zero unless the directory stack is empty. When rotating the directory stack, pushd returns zero unless the directory stack is empty or n specifies a non-existent directory stack element.

If the pushd command is successful, bash runs dirs to show the final contents of the directory stack.


pwd ๐Ÿงญ

pwd [-LP]

Print the absolute pathname of the current working directory. The pathname printed contains no symbolic links if the -P option is supplied or the -o physical option to the set builtin command is enabled. If the -L option is used, the pathname printed may contain symbolic links. The return status is 0 unless an error occurs while reading the name of the current directory or an invalid option is supplied.


read ๐Ÿ“–

read [-Eers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]

Read one line from the standard input, or from the file descriptor fd supplied as an argument to the -u option, split it into words as described in bash (1) under Word Splitting, and assign the first word to the first name, the second word to the second name, and so on. If there are more words than names, the remaining words and their intervening delimiters are assigned to the last name. If there are fewer words read from the input stream than names, the remaining names are assigned empty values. The characters in the value of the IFS variable are used to split the line into words using the same rules the shell uses for expansion (described in bash (1) under Word Splitting). The backslash character (\) removes any special meaning for the next character read and is used for line continuation.

Options, if supplied, have the following meanings:

  • -a aname โ€” The words are assigned to sequential indices of the array variable aname, starting at 0. aname is unset before any new values are assigned. Other name arguments are ignored.
  • -d delim โ€” The first character of delim terminates the input line, rather than newline. If delim is the empty string, read will terminate a line when it reads a NUL character.
  • -e โ€” If the standard input is coming from a terminal, read uses readline (see READLINE in bash(1)) to obtain the line. Readline uses the current (or default, if line editing was not previously active) editing settings, but uses readline's default filename completion.
  • -E โ€” If the standard input is coming from a terminal, read uses readline (see READLINE in bash(1)) to obtain the line. Readline uses the current (or default, if line editing was not previously active) editing settings, but uses bash's default completion, including programmable completion.
  • -i text โ€” If readline is being used to read the line, read places text into the editing buffer before editing begins.
  • -n nchars โ€” read returns after reading nchars characters rather than waiting for a complete line of input, unless it encounters EOF or read times out, but honors a delimiter if it reads fewer than nchars characters before the delimiter.
  • -N nchars โ€” read returns after reading exactly nchars characters rather than waiting for a complete line of input, unless it encounters EOF or read times out. Any delimiter characters in the input are not treated specially and do not cause read to return until it has read nchars characters. The result is not split on the characters in IFS; the intent is that the variable is assigned exactly the characters read (with the exception of backslash; see the -r option below).
  • -p prompt โ€” Display prompt on standard error, without a trailing newline, before attempting to read any input, but only if input is coming from a terminal.
  • -r โ€” Backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not then be used as a line continuation.
  • -s โ€” Silent mode. If input is coming from a terminal, characters are not echoed.
  • -t timeout โ€” Cause read to time out and return failure if it does not read a complete line of input (or a specified number of characters) within timeout seconds. timeout may be a decimal number with a fractional portion following the decimal point. This option is only effective if read is reading input from a terminal, pipe, or other special file; it has no effect when reading from regular files. If read times out, it saves any partial input read into the specified variable name, and the exit status is greater than 128. If timeout is 0, read returns immediately, without trying to read any data. In this case, the exit status is 0 if input is available on the specified file descriptor, or the read will return EOF, non-zero otherwise.
  • -u fd โ€” Read input from file descriptor fd instead of the standard input.

Other than the case where delim is the empty string, read ignores any NUL characters in the input.

If no names are supplied, read assigns the line read, without the ending delimiter but otherwise unmodified, to the variable REPLY.

The exit status is zero, unless end-of-file is encountered, read times out (in which case the status is greater than 128), a variable assignment error (such as assigning to a readonly variable) occurs, or an invalid file descriptor is supplied as the argument to -u.

  • readonly [-aAf] [-p] [name[=word] ...]

okay so readonly is literally the "no take-backsies" button ๐Ÿ’… the names you hand it get marked readonly, and after that? nobody's changing them. not a later assignment, not unset. they're frozen, bestie. ๐ŸงŠ

  • If you throw in -f, then each name is talking about a shell function, not a variable.
  • -a locks the names down to indexed arrays only.
  • -A locks them to associative arrays only.
  • And if you somehow pass both -a and -A? -A wins. it takes precedence, no debate.

If you give it no name arguments at all, or if you pass -p, it just prints out a list of all the readonly names. the other options can narrow that output down to a subset of the readonly name set. and -p is the cute one โ€” it displays everything in a format that's reusable as input. so you can literally copy it back in. โœจ

also readonly lets you set a variable's value at the same time as you change the readonly attribute, just by following the variable name with =value. that sets the value of the variable to value while it's modifying the readonly attribute. two birds, one slay. ๐Ÿฆ‹

The return status is 0 unless:

  • an invalid option shows up ๐Ÿ˜ญ
  • one of the names isn't a valid shell variable name
  • or you supplied -f with a name that isn't a function

  • return [n]

the way that return just stops executing a shell function or a sourced file and hands the value in n back to whoever called it. ๐Ÿ’Œ

If n is omitted, the return status is just the return status of the last command executed.

Now here's the โœจ nuance โœจ bestie:

  • If return gets executed by a trap handler, the last command used to determine the status is the last command executed before the trap handler.
  • If return is executed during a DEBUG trap, the last command used to determine the status is the last command executed by the trap handler before return was invoked. ๐Ÿ™ˆ

When return is used to terminate execution of a script being run by the . (source) command, it makes the shell stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script. And if n is supplied, the return value is its least significant 8 bits. periodt. ๐Ÿ‘‘

Any command associated with the RETURN trap runs before execution resumes after the function or script. ๐ŸŒธ

The return status is non-zero if return is given a non-numeric argument, or if it's used outside a function and not during execution of a script by . or source. ๐Ÿ’€


  • set [-abefhkmnptuvxBCEHPT] [-o option-name] [--] [-] [arg ...]
  • set [+abefhkmnptuvxBCEHPT] [+o option-name] [--] [-] [arg ...]
  • set -o
  • set +o

okay so with no options, set displays the name and value of every single shell variable, in a format that can be reused as input for setting or resetting the currently-set variables. so yeah, it's basically a screenshot of your whole variable vibe check. ๐Ÿ“ธ

read-only variables cannot be reset. not even a little. ๐Ÿ™…

In posix mode, only shell variables get listed. and the output is sorted according to the current locale.

When you do specify options, they set or unset shell attributes. Any arguments left over after option processing get treated as values for the positional parameters and get assigned, in order, to $1, $2, ..., $n. ๐ŸŽ€

Options, if specified, mean this:

  • -a โ€” Every variable or function that gets created or modified is given the export attribute and marked for export to the environment of subsequent commands.
  • -b โ€” Report the status of terminated background jobs immediately, rather than before the next primary prompt or after a foreground command terminates. This is only effective when job control is enabled.
  • -e โ€” Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL GRAMMAR in bash(1)), exits with a non-zero status. ๐Ÿ”ฅ

BUT โ€” and this is the part everyone gets wrong, so listen up bestie โ€” the shell does not exit if the command that fails is:

  • part of the command list immediately following a while or until reserved word
  • part of the test following the if or elif reserved words
  • part of any command executed in a && or || list except the command following the final && or ||
  • any command in a pipeline but the last (subject to the state of the pipefail shell option)
  • or if the command's return value is being inverted with !

If a compound command other than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit. A trap on ERR, if set, is executed before the shell exits.

This option applies to the shell environment and each subshell environment separately (see COMMAND EXECUTION ENVIRONMENT in bash(1)), and may cause subshells to exit before executing all the commands in the subshell. so watch out. ๐Ÿ˜ญ

If a compound command or a shell function runs somewhere that -e is being ignored, then none of the commands inside that compound command or function body get touched by the -e setting โ€” even if -e is set and a command returns a failure status. And if a compound command or shell function sets -e while it's executing in a context where -e is ignored, that setting does literally nothing until the compound command โ€” or the command containing the function call โ€” completes. ๐Ÿ˜ค periodt.

  • -f โ€” disable pathname expansion. no more globbing, bestie ๐ŸŒธ
  • -h โ€” remember where commands live as they get looked up for execution. this one is on by default โœจ
  • -k โ€” every argument that looks like an assignment statement goes into the environment for a command, not just the ones that come before the command name. ๐Ÿ‘‘
  • -m โ€” Monitor mode. job control is ON. this is on by default for interactive shells on systems that support it (peep JOB CONTROL in bash(1)). all processes run in their own separate process group. and when a background job finishes, the shell prints a line with its exit status. ๐Ÿ’…
  • -n โ€” read commands but do not execute them. great for syntax-checking a shell script. interactive shells just ignore this one. ๐Ÿ™ˆ
  • -o option-name โ€” and option-name can be any one of these lil guys:
    • allexport โ€” same as -a.
    • braceexpand โ€” same as -B.
    • emacs โ€” use an emacs-style command line editing interface. on by default when the shell is interactive, unless the shell was started with the --noediting option. this also affects the editing interface used for read -e. ๐ŸŽ€
    • errexit โ€” same as -e.
    • errtrace โ€” same as -E.
    • functrace โ€” same as -T.
    • hashall โ€” same as -h.
    • histexpand โ€” same as -H.
    • history โ€” enable command history, as described in bash(1) under HISTORY. on by default in interactive shells. ๐Ÿฆ‹
    • ignoreeof โ€” the effect is as if the shell command had been executed (see Shell Variables in bash(1)).
    • keyword โ€” same as -k.
    • monitor โ€” same as -m.
    • noclobber โ€” same as -C.
    • noexec โ€” same as -n.
    • noglob โ€” same as -f.
    • nolog โ€” currently ignored. she's just vibing ๐Ÿ’€
    • 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 every command in the pipeline exits successfully. this one is disabled by default.
    • posix โ€” enable posix mode; change the behavior of bash wherever the default operation differs from the POSIX standard so it matches the standard. see SEE ALSO in bash(1) for a reference to a document that details how posix mode affects bash's behavior. ๐Ÿ“œ
    • privileged โ€” same as -p.
    • verbose โ€” same as -v.
    • vi โ€” use a vi-style command line editing interface. this also affects the editing interface used for read -e. ๐ŸŒˆ
    • xtrace โ€” same as -x.

If -o is supplied with no option-name, set prints the current shell option settings. and if +o is supplied with no option-name, set prints a whole series of set commands that recreate the current option settings on the standard output. cute, right? ๐Ÿ’–

  • -p โ€” turn on privileged mode. in this mode the shell does not read the $ENV and $BASH_ENV files, shell functions are not inherited from the environment, and the SHELLOPTS, BASHOPTS, CDPATH, and GLOBIGNORE variables โ€” if they show up in the environment โ€” are 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. ๐Ÿซถ
  • -r โ€” enable restricted shell mode. once this one is set, it cannot be unset. no takebacks. ๐Ÿ™…โ€โ™€๏ธ
  • -t โ€” exit after reading and executing one command.
  • -u โ€” treat unset variables and parameters other than the special parameters and or array variables subscripted with or as an error when performing parameter expansion. if expansion is attempted on an unset variable or parameter, the shell prints an error message and, if it's not interactive, exits with a non-zero status. ๐Ÿ˜ญ
  • -v โ€” print shell input lines as they're 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, to the standard error. ๐Ÿ”ฅ
  • -B โ€” the shell performs brace expansion (see Brace Expansion in bash(1)). this is on by default. โœจ
  • -C โ€” if set, bash does not overwrite an existing file with the >, >&, and <> redirection operators. using the redirection operator >| instead of > will override this and force the creation of an output file. ๐Ÿ’…
  • -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 resolve 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, unset the positional parameters. otherwise, set the positional parameters to the args, even if some of them begin with a -.
  • - โ€” signal the end of options, and assign all remaining args to the positional parameters. the -x and -v options are turned off. if there are no args, the positional parameters remain unchanged.

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 zero unless an invalid option is encountered. ๐Ÿ’–


shift [n] โœจ

Rename positional parameters from n+1 ... to $1 .... the parameters represented by the numbers $# down to $#-n+1 get unset. n has to be a non-negative number less than or equal to $#. if n is 0, no parameters are changed. if n isn't given, it's assumed to be 1. if n is greater than $#, the positional parameters are not changed. the return status is greater than zero if n is greater than $# or less than zero; otherwise 0. ๐ŸŽ€

shopt [-pqsu] [-o] [optname ...] ๐Ÿฆ‹

Toggle the values of settings controlling optional shell behavior. the settings can be either the ones listed below, or โ€” if the -o option is used โ€” those available with the -o option to the set builtin command. ๐Ÿ‘‘

With no options, or with the -p option, display a list of all settable options, with an indication of whether or not each one is set; if any optnames are supplied, the output is restricted to those options. the -p option displays output in a form that may be reused as input. ๐Ÿ’…

Other options have the following meanings:

  • -s โ€” enable (set) each optname.
  • -u โ€” disable (unset) each optname.
  • -q โ€” suppresses normal output (quiet mode); the return status indicates whether the optname is set or unset. if multiple optname arguments are supplied with -q, the return status is zero if all optnames are enabled; non-zero otherwise. ๐Ÿคซ
  • -o โ€” restricts the values of optname to be those defined for the -o option to the set builtin.

If either -s or -u is used with no optname arguments, shopt shows only those options which are set or unset, respectively. unless otherwise noted, the shopt options are disabled (unset) by default.

The return status when listing options is zero if all optnames are enabled, non-zero otherwise. when setting or unsetting options, the return status is zero unless an optname is not a valid shell option.

The list of shopt options is: ๐ŸŒˆ

  • array_expand_once โ€” turn this on and the shell stops evaluating your associative and indexed array subscripts over and over. Like, it suppresses multiple evaluation during arithmetic expression evaluation, while executing builtins that can perform variable assignments, and while executing builtins that perform array dereferencing. one and done, bestie ๐Ÿ’…
  • assoc_expand_once โ€” deprecated, babe ๐Ÿซ  โ€” it's literally just a synonym for array_expand_once.
  • autocd โ€” if you set this, a command name that is the name of a directory gets executed as if it were the argument to the cd command. This option is only used by interactive shells. โœจ
  • bash_source_fullpath โ€” if you set this, the filenames added to the BASH_SOURCE array variable get converted to full pathnames (peep Shell Variables above ๐Ÿ‘€).
  • cdable_vars โ€” if you set this, an argument to the cd builtin command that isn't a directory is assumed to be the name of a variable whose value is the directory to change to. iconic lazy-girl behavior tbh ๐Ÿ’–
  • cdspell โ€” if you set this, the cd command tries to correct minor errors in the spelling of a directory component. "Minor errors" means transposed characters, a missing character, and one extra character. If cd corrects the directory name, it prints the corrected filename and the command proceeds. This option is only used by interactive shells. ๐ŸŒธ
  • checkhash โ€” if you set this, bash checks that a command found in the hash table actually exists before trying to execute it. If a hashed command no longer exists, bash performs a normal path search. ๐Ÿฆ‹
  • checkjobs โ€” if you set this, bash lists the status of any stopped and running jobs before exiting an interactive shell. If any jobs are running, bash defers the exit until a second exit is attempted without an intervening command (see JOB CONTROL in bash(1)). The shell always postpones exiting if any jobs are stopped. ๐Ÿ’€
  • checkwinsize โ€” if you set this, bash checks the window size after each external (non-builtin) command and, if necessary, updates the values of LINES and COLUMNS, using the file descriptor associated with the standard error if it is a terminal. This option is enabled by default. ๐ŸŽ€
  • cmdhist โ€” if you set this, bash attempts to save all lines of a multiple-line command in the same history entry. This allows easy re-editing of multi-line commands. This option is enabled by default, but only has an effect if command history is enabled, as described in bash(1) under HISTORY. ๐Ÿ“œ
  • compat31, compat32, compat40, compat41, compat42, compat43, compat44 โ€” these control aspects of the shell's compatibility mode (see SHELL COMPATIBILITY MODE in bash(1)). the time-travel buttons fr fr โณ
  • complete_fullquote โ€” if you set this, bash quotes all shell metacharacters in filenames and directory names when performing completion. If it's not set, bash removes metacharacters such as the dollar sign from the set of characters that will be quoted in completed filenames when these metacharacters appear in shell variable references in words to be completed. This means that dollar signs in variable names that expand to directories will not be quoted; however, any dollar signs appearing in filenames will not be quoted, either. This is active only when bash is using backslashes to quote completed filenames. This variable is set by default, which is the default bash behavior in versions through 4.2. ๐Ÿ’…
  • direxpand โ€” if you set this, bash replaces directory names with the results of word expansion when performing filename completion. This changes the contents of the readline editing buffer. If it's not set, bash attempts to preserve what the user typed. โœ๏ธ
  • dirspell โ€” if you set this, bash attempts spelling correction on directory names during word completion if the directory name initially supplied doesn't exist. ๐Ÿ”
  • dotglob โ€” if you set this, bash includes filenames beginning with a in the results of pathname expansion. The filenames and must always be matched explicitly, even if dotglob is set. ๐Ÿ•ต๏ธ
  • execfail โ€” if you set this, a non-interactive shell will not exit if it can't execute the file specified as an argument to the exec builtin. An interactive shell does not exit if exec fails. ๐Ÿ˜Œ
  • expand_aliases โ€” if you set this, aliases are expanded as described in bash(1) under ALIASES. This option is enabled by default for interactive shells. ๐Ÿช„
  • extdebug โ€” if this is set at shell invocation, or in a shell startup file, it arranges to execute the debugger profile before the shell starts, identical to the --debugger option. If it's set after invocation, behavior intended for use by debuggers is enabled:
    1. The -F option to the declare builtin displays the source file name and line number corresponding to each function name supplied as an argument.
    2. If the command run by the DEBUG trap returns a non-zero value, the next command is skipped and not executed.
    3. If the command run by the DEBUG trap returns a value of 2, and the shell is executing in a subroutine (a shell function or a shell script executed by the . or source builtins), the shell simulates a call to return.
    4. BASH_ARGC and BASH_ARGV are updated as described in their descriptions in bash(1)).
    5. Function tracing is enabled: command substitution, shell functions, and subshells invoked with ( command ) inherit the DEBUG and RETURN traps.
    6. Error tracing is enabled: command substitution, shell functions, and subshells invoked with ( command ) inherit the ERR trap.
  • extglob โ€” if you set this, it enables the extended pattern matching features described in bash(1) under Pathname Expansion. ๐Ÿ”ฅ
  • extquote โ€” if you set this, $string and $string quoting is performed within ${parameter} expansions enclosed in double quotes. This option is enabled by default. โœจ
  • failglob โ€” if you set this, patterns which fail to match filenames during pathname expansion result in an expansion error. ๐Ÿ˜ญ
  • force_fignore โ€” if you set this, the suffixes specified by the FIGNORE shell variable cause words to be ignored when performing word completion even if the ignored words are the only possible completions. See Shell Variables in bash(1) for a description of FIGNORE. This option is enabled by default. ๐Ÿ™ˆ
  • globasciiranges โ€” if you set this, range expressions used in pattern matching bracket expressions (see Pattern Matching in bash(1)) behave as if in the traditional C locale when performing comparisons. That is, pattern matching does not take the current locale's collating sequence into account, so b will not collate between A and B, and upper-case and lower-case ASCII characters will collate together. ๐ŸŒˆ
  • globskipdots โ€” if you set this, pathname expansion will never match the filenames and even if the pattern begins with a This option is enabled by default. ๐ŸŽ€
  • globstar โ€” if you set this, the pattern ** used in a pathname expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a /, only directories and subdirectories match. the ** glow-up, obsessed โญ
  • gnu_errfmt โ€” if you set this, shell error messages are written in the standard GNU error message format. ๐Ÿ“
  • histappend โ€” if you set this, the history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file. ๐Ÿ’–
  • histreedit โ€” if you set this, and readline is being used, the user is given the opportunity to re-edit a failed history substitution. ๐Ÿซถ
  • histverify โ€” if you set this, and readline is being used, the results of history substitution are not immediately passed to the shell parser. Instead, the resulting line is loaded into the readline editing buffer, allowing further modification. โœ๏ธ
  • hostcomplete โ€” if you set this, and readline is being used, bash will attempt to perform hostname completion when a word containing a @ is being completed (see Completing under READLINE in bash(1)). This is enabled by default. ๐ŸŒ
  • huponexit โ€” if you set this, bash will send SIGHUP to all jobs when an interactive login shell exits. ๐Ÿ’€
  • inherit_errexit โ€” if you set this, command substitution inherits the value of the errexit option, instead of unsetting it in the subshell environment. This option is enabled when posix mode is enabled. ๐Ÿงš
  • interactive_comments โ€” in an interactive shell, a word beginning with # causes that word and all remaining characters on that line to be ignored, as in a non-interactive shell (see COMMENTS in bash(1)). This option is enabled by default. ๐Ÿ’ฌ
  • lastpipe โ€” if you set this, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment. ๐Ÿ‘‘
  • lithist โ€” if this is on and cmdhist is enabled too, then multi-line commands get saved to your history with actual embedded newlines in them, instead of squishing them together with semicolon separators wherever that's possible. cleaner history, cleaner life โœจ
  • localvar_inherit โ€” if set, local variables inherit the value and the attributes of a variable with the same name that exists at a previous scope, and they do that before any new value gets assigned. the nameref attribute is not inherited tho ๐Ÿซถ
  • localvar_unset โ€” if set, calling unset on local variables in previous function scopes marks them so that subsequent lookups find them unset until that function returns. This is identical to the behavior of unsetting local variables at the current function scope. same vibe, different scope ๐Ÿ’œ
  • login_shell โ€” the shell sets this one itself if it was started as a login shell (see INVOCATION in bash(1)). the value may not be changed ๐Ÿšซ
  • mailwarn โ€” if set, and a file that bash is checking for mail has been accessed since the last time it was checked, bash displays the message
  • no_empty_cmd_completion โ€” if set, and readline is being used, bash does not search PATH for possible completions when completion is attempted on an empty line. no more accidental tab-spam ๐Ÿ™ˆ
  • nocaseglob โ€” if set, bash matches filenames in a case-insensitive fashion when performing pathname expansion (see Pathname Expansion in bash(1)). shouty filenames welcome ๐ŸŒธ
  • nocasematch โ€” if set, bash matches patterns in a case-insensitive fashion when performing matching while executing case or [[ conditional commands, when performing pattern substitution word expansions, or when filtering possible completions as part of programmable completion. everywhere at once bestie ๐Ÿ’…
  • noexpand_translation โ€” if set, bash encloses the translated results of $... quoting in single quotes instead of double quotes. If the string is not translated, this has no effect. only matters when there's actually a translation ๐Ÿฆ‹
  • nullglob โ€” if set, pathname expansion patterns which match no files (see Pathname Expansion in bash(1)) expand to nothing and are removed, rather than expanding to themselves. the glow-up from literal *.txt sitting there being sad โœจ
  • patsub_replacement โ€” if set, bash expands occurrences of & in the replacement string of pattern substitution to the text matched by the pattern, as described under Parameter Expansion in bash(1). this option is enabled by default ๐Ÿ‘‘
  • progcomp โ€” if set, enable the programmable completion facilities (see Programmable Completion in bash(1)). this option is enabled by default โญ
  • progcomp_alias โ€” if set, and programmable completion is enabled, bash treats a command name that doesn't have any completions as a possible alias and attempts alias expansion. If it has an alias, bash attempts programmable completion using the command word resulting from the expanded alias. detective mode for your aliases ๐Ÿ•ต๏ธ
  • promptvars โ€” if set, prompt strings undergo parameter expansion, command substitution, arithmetic expansion, and quote removal after being expanded as described in PROMPTING in bash(1). this option is enabled by default ๐Ÿ’–
  • restricted_shell โ€” the shell sets this option if it is started in restricted mode (see RESTRICTED SHELL in bash(1)). the value may not be changed. It is not reset when the startup files are executed, which is the whole point โ€” it lets your startup files discover whether or not a shell is restricted. ๐Ÿ”’
  • shift_verbose โ€” if set, the shift builtin prints an error message when the shift count exceeds the number of positional parameters. receipts, loudly ๐Ÿ“ข
  • sourcepath โ€” if set, the . (source) builtin uses the value of PATH to find the directory containing the file supplied as an argument when the -p option is not supplied. this option is enabled by default ๐ŸŽ€
  • varredir_close โ€” if set, the shell automatically closes file descriptors assigned using the {varname} redirection syntax (see REDIRECTION in bash(1)) instead of leaving them open when the command completes. tidy girl behavior ๐Ÿงš
  • xpg_echo โ€” if set, the echo builtin expands backslash-escape sequences by default. If the posix shell option is also enabled, echo does not interpret any options. double flag combo, be careful ๐ŸŒˆ

๐Ÿ˜ด suspend [-f]

suspend [-f]

Suspend the execution of this shell until it receives a SIGCONT signal. naptime for your whole session ๐Ÿ’ค

A login shell, or a shell without job control enabled, cannot be suspended. The -f option will override this and force the suspension anyway. no job control? no suspend. periodt. ๐Ÿ˜ญ

The return status is 0 unless the shell is a login shell or job control is not enabled and -f is not supplied. ๐Ÿ”ฅ


๐Ÿงช test expr / [ expr ]

test expr
[ expr ]

Return a status of 0 (true) or 1 (false) depending on the evaluation of the conditional expression expr. every operator and operand must be its own separate argument โ€” yes, the spacing is load-bearing bestie, it's always the spacing ๐Ÿซถ

Expressions are composed of the primaries described in bash(1) under CONDITIONAL EXPRESSIONS.

test does not accept any options, and it does not accept and ignore an argument of -- as signifying the end of options. so don't try it, it's not that kind of party ๐Ÿ’…

Expressions may be combined using the following operators, listed in decreasing order of precedence. The evaluation depends on the number of arguments; see below. test uses operator precedence when there are five or more arguments. โญ

  • ! expr โ€” True if expr is false.
  • ( expr ) โ€” Returns the value of expr. This may be used to override normal operator precedence.
  • expr1 -a expr2 โ€” True if both expr1 and expr2 are true.
  • expr1 -o expr2 โ€” True if either expr1 or expr2 is true.

test and [ evaluate conditional expressions using a set of rules based on the number of arguments. the argument-count lore is REAL and it is chaotic ๐ŸŒˆ

0 arguments

The expression is false. nothing to see here ๐Ÿ’€

1 argument

The expression is true if and only if the argument is not null. non-empty = slay โœจ

2 arguments

  • If the first argument is !, the expression is true if and only if the second argument is null.
  • If the first argument is one of the unary conditional operators listed in bash(1) under CONDITIONAL EXPRESSIONS, the expression is true if the unary test is true.
  • If the first argument is not a valid unary conditional operator, the expression is false. no operator, no truth ๐Ÿšซ

3 arguments

The following conditions are applied in the order listed. ๐Ÿ‘‘

  1. If the second argument is one of the binary conditional operators listed in bash(1) under CONDITIONAL EXPRESSIONS, the result of the expression is the result of the binary test using the first and third arguments as operands. The -a and -o operators are considered binary operators when there are three arguments.
  2. If the first argument is !, the value is the negation of the two-argument test using the second and third arguments.
  3. If the first argument is exactly ( and the third argument is exactly ), the result is the one-argument test of the second argument.
  4. Otherwise, the expression is false. sorry bestie ๐Ÿ˜ญ

4 arguments

The following conditions are applied in the order listed.

  1. If the first argument is !, the result is the negation of the three-argument expression composed of the remaining arguments.
  2. If the first argument is exactly ( and the fourth argument is exactly ), the result is the two-argument test of the second and third arguments.
  3. Otherwise, the expression is parsed and evaluated according to precedence using the rules listed above. ๐ŸŒธ

5 or more arguments

The expression is parsed and evaluated according to precedence using the rules listed above. same energy, more arguments ๐Ÿ’…


When the shell is in posix mode, or if the expression is part of the [[ command, the < and > operators sort using the current locale. If the shell is not in posix mode, the test and [ commands sort lexicographically using ASCII ordering. locale vs ASCII, pick your fighter ๐Ÿฆ‹

โš ๏ธ BIG warning bestie, please read this one. The historical operator-precedence parsing with 4 or more arguments can lead to ambiguities when it encounters strings that look like primaries. The POSIX standard has deprecated the -a and -o primaries and enclosing expressions within parentheses. Scripts should no longer use them. It's much more reliable to restrict test invocations to a single primary, and to replace uses of -a and -o with the shell's && and || list operators. do this and your scripts will stop gaslighting you, fr fr ๐Ÿซถ

โฑ๏ธ times

times

Print the accumulated user and system times for the shell and for processes run from the shell. The return status is 0. numbers go brrr ๐Ÿ“Š


๐Ÿชค trap [-lpP] [[action] sigspec ...]

trap [-lpP] [[action] sigspec ...]

The action is a command that is read and executed when the shell receives any of the signals sigspec. your little signal-handling bestie ๐Ÿ’œ

If action is absent (and there is a single sigspec) or -, each specified sigspec is reset to the value it had when the shell was started. ๐Ÿ”„

If action is the null string, the signal specified by each sigspec is ignored by the shell and by the commands it invokes. not handled โ€” actually ignored, there's a difference and it matters โœจ

If you don't hand it any arguments at all, trap will spill the tea on the actions attached to every trapped signal โ€” shown as a bunch of trap commands you can literally reuse as shell input to restore the current signal dispositions. ๐Ÿ’…

If -p is given and action isn't there, then trap shows the actions tied to each sigspec โ€” or, if you didn't pass any sigspecs at all, for all the trapped signals โ€” again as a set of trap commands reusable as shell input to restore the current signal dispositions. The -P option acts similarly, but only shows the actions for each sigspec argument. Heads up: -P needs at least one sigspec argument, no exceptions bestie. ๐Ÿซถ The -P or -p options can be used inside a subshell environment (like command substitution) and, as long as you use them before trap is used to change a signal's handling, they'll show you the state of the parent's traps.

The -l option prints a list of signal names plus their matching numbers. Each sigspec is either a signal name defined in <signal.h>, or a signal number. Signal names are case insensitive and the SIG prefix is optional. If you supply -l with no sigspec arguments, it prints a list of valid signal names. โœจ

If a sigspec is EXIT (0), then action runs on exit from the shell. If a sigspec is DEBUG, action runs before every simple command, for command, case command, select command, (( arithmetic command, [[ conditional command, arithmetic for command, and before the first command executes in a shell function (see SHELL GRAMMAR in bash(1)). Go read the description of the extdebug shell option (see shopt in bash(1)) for the details of how it messes with the DEBUG trap. If a sigspec is RETURN, action runs every single time a shell function or a script executed with the . or source builtins finishes running. ๐Ÿ’–

If a sigspec is ERR, action runs whenever a pipeline (which can be just a single simple command), a list, or a compound command returns a non-zero exit status โ€” but only under these conditions, okay? The ERR trap does not run if the failed command is:

  • part of the command list immediately following a while or until reserved word,
  • part of the test in an if statement,
  • part of a command executed in a && or || list, except the command following the final && or ||,
  • any command in a pipeline but the last (this depends on the state of the pipefail shell option),
  • or if the command's return value is being inverted using !.

These are literally the same conditions obeyed by the errexit (-e) option. ๐ŸŽ€

When the shell isn't interactive, signals ignored upon entry to the shell cannot be trapped or reset. Interactive shells do permit trapping signals ignored on entry. Trapped signals that aren't being ignored get reset to their original values in a subshell or subshell environment when one is created. The return status is false if any sigspec is invalid; otherwise trap returns true. ๐Ÿ‘‘


true

Does nothing, returns a 0 status. Iconic. Effortless. No notes. ๐Ÿ’…


type

type [-aftpP] name [name ...]

Tells you how each name would be interpreted if you used it as a command name. ๐Ÿ”

With the -t option, type prints a string that's one of alias, keyword, function, builtin, or file โ€” depending on whether name is an alias, shell reserved word, function, builtin, or executable file, respectively. If the name isn't found, type prints nothing and returns a non-zero exit status. ๐Ÿซฅ

With the -p option, type either returns the pathname of the executable file that would be found by searching $PATH for name, or nothing if it wouldn't return a file. The -P option forces a PATH search for each name, even if it wouldn't return a file. If name is present in the table of hashed commands, -p and -P print the hashed value โ€” which is not necessarily the file that appears first in PATH. ๐Ÿ™ˆ

With the -a option, type prints all of the places that contain a command named name. That includes aliases, reserved words, functions, and builtins โ€” but you can also hand it the path search options (-p and -P) to restrict the output to executable files only. Note that type does not consult the table of hashed commands when using -a with -p, and only performs a PATH search for name. ๐Ÿ’€

The -f option suppresses shell function lookup, just like the command builtin does. type returns true if all of the arguments are found, false if any are not found. ๐ŸŒธ


ulimit

ulimit [-HS] -a
ulimit [-HS] [-bcdefiklmnpqrstuvxPRT [limit]]

Gives you control over the resources available to the shell and to processes it starts โ€” on systems that allow such control, anyway. ๐ŸŽ›๏ธ

The -H and -S options specify whether the hard or soft limit gets set for the given resource. A hard limit cannot be increased by a non-root user once it's set; a soft limit may be increased up to the value of the hard limit. If neither -H nor -S is specified, ulimit sets both the soft and hard limits. โš–๏ธ

The value of limit can be a number in the unit specified for the resource, or one of the special values hard, soft, or unlimited โ€” which stand for the current hard limit, the current soft limit, and no limit, respectively. If limit is omitted, ulimit prints the current value of the soft limit of the resource, unless the -H option is given. When more than one resource is specified, the limit name and unit (if appropriate) are printed before the value. ๐Ÿงพ

Other options get interpreted like this:

  • -a โ€” Report all current limits; no limits are set.
  • -b โ€” The maximum socket buffer size.
  • -c โ€” The maximum size of core files created.
  • -d โ€” The maximum size of a process's data segment.
  • -e โ€” The maximum scheduling priority (
  • -f โ€” The maximum size of files written by the shell and its children.
  • -i โ€” The maximum number of pending signals.
  • -k โ€” The maximum number of kqueues that may be allocated.
  • -l โ€” The maximum size that may be locked into memory.
  • -m โ€” The maximum resident set size (many systems do not honor this limit).
  • -n โ€” The maximum number of open file descriptors (most systems do not allow this value to be set).
  • -p โ€” The pipe size in 512-byte blocks (this may not be set).
  • -q โ€” The maximum number of bytes in POSIX message queues.
  • -r โ€” The maximum real-time scheduling priority.
  • -s โ€” The maximum stack size.
  • -t โ€” The maximum amount of cpu time in seconds.
  • -u โ€” The maximum number of processes available to a single user.
  • -v โ€” The maximum amount of virtual memory available to the shell and, on some systems, to its children.
  • -x โ€” The maximum number of file locks.
  • -P โ€” The maximum number of pseudoterminals.
  • -R โ€” The maximum time a real-time process can run before blocking, in microseconds.
  • -T โ€” The maximum number of threads.

If limit is supplied and -a is not used, then limit is the new value of the specified resource. If no option is supplied at all, then -f is assumed. ๐ŸŽฏ

Values are in 1024-byte increments, except for -t, which is in seconds; -R, which is in microseconds; -p, which is in units of 512-byte blocks; -P, -T, -b, -k, -n, and -u, which are unscaled values; and, when in posix mode, -c and -f, which are in 512-byte increments. The return status is 0 unless an invalid option or argument is supplied, or an error occurs while setting a new limit. โญ


umask

umask [-p] [-S] [mode]

Sets the user file-creation mask to mode. If mode begins with a digit, it's interpreted as an octal number; otherwise it's interpreted as a symbolic mode mask similar to the one chmod(1) accepts. If mode is omitted, umask prints the current value of the mask. ๐ŸŽญ

The -S option without a mode argument prints the mask in a symbolic format; the default output is an octal number. If the -p option is supplied and mode is omitted, the output comes in a form that can be reused as input. The return status is zero if the mode was successfully changed or if no mode argument was supplied, and non-zero otherwise. ๐Ÿ’œ


unalias

unalias [-a] [name ...]

Removes each name from the list of defined aliases. If -a is supplied, it removes all alias definitions. The return value is true unless a supplied name is not a defined alias. ๐Ÿงน


unset

unset [-fv] [-n] [name ...]

For each name, it removes the corresponding variable or function. ๐Ÿ”ฅ

  • If the -v option is given, each name refers to a shell variable, and that variable gets removed.
  • If -f is specified, each name refers to a shell function, and the function definition gets removed.
  • If the -n option is supplied and name is a variable with the nameref attribute, then name itself will be unset rather than the variable it references. Note: -n has no effect if the -f option is supplied. ๐Ÿ™…

Read-only variables and functions may not be unset. When variables or functions get removed, they're also removed from the environment passed to subsequent commands. If no options are supplied, each name refers to a variable; if there's no variable by that name, a function with that name, if any, gets unset. Some shell variables may not be unset. โš ๏ธ

If any of BASH_ALIASES, BASH_ARGV0, BASH_CMDS, BASH_COMMAND, BASH_SUBSHELL, BASHPID, COMP_WORDBREAKS, DIRSTACK, EPOCHREALTIME, EPOCHSECONDS, FUNCNAME, GROUPS, HISTCMD, LINENO, RANDOM, SECONDS, or SRANDOM are unset, they lose their special properties โ€” even if they are subsequently reset. ๐Ÿ˜ญ The exit status is true unless a name is readonly or may not be unset.


wait

wait [-fn] [-p varname] [id ...]

Waits for each specified child process id and returns the termination status of the last id. Each id may be a process ID pid or a job specification jobspec; if a jobspec is supplied, wait waits for all processes in the job. ๐Ÿซถ

If no options or ids are supplied, wait waits for all running background jobs and the last-executed process substitution, if its process id is the same as $!, and the return status is zero. ๐ŸŒˆ

  • -n โ€” bestie, with this one wait doesn't wait for everything, it waits for any one of the given ids to finish and hands you its exit status. And if you gave it no ids at all? It waits for any job or process substitution to complete. Iconic low-effort behaviour. ๐Ÿ’…
  • -p โ€” this one is the โœจspecialโœจ one. wait takes the process or job identifier of the job whose exit status it just returned and assigns it to the variable varname named by the option argument. That variable cannot be readonly, and it will be unset initially, before any assignment happens. Real talk: this is only useful when you pair it with -n. ๐Ÿ‘‘
  • -f โ€” when job control is enabled, supplying this forces wait to wait for each id to actually terminate before returning its status, instead of bailing out the moment it changes status.

So like, the return status tea โ˜•: if none of the ids specify one of the shell's active child processes, the return status is 127. If wait gets interrupted by a signal, any varname will remain unset, and the return status will be greater than 128, exactly as described under SIGNALS in bash(1). Otherwise, the return status is just the exit status of the last id. Periodt. ๐Ÿซถ


๐ŸŒˆ SHELL COMPATIBILITY MODE ๐ŸŒˆ

Bash-4.0 introduced the concept of a shell compatibility level, and it's specified as a set of options to the shopt builtin (compat31, compat32, compat40, compat41, and so on). Heads up: there is only one current compatibility level โ€” each option is mutually exclusive. The whole idea is to let you select behaviour from previous versions that's incompatible with newer versions, so you can migrate your scripts to current features and behaviour at your own pace. It's intended to be a temporary solution, fr fr. ๐Ÿ•ฐ๏ธ

This section does not mention behavior that is standard for a particular version (e.g., setting compat32 means that quoting the right hand side of the regexp matching operator quotes special regexp characters in the word, which is default behavior in bash-3.2 and subsequent versions).

Now the part that lowkey trips everyone up ๐ŸŒ€: if a user enables, say, compat32, it may affect the behavior of other compatibility levels up to and including the current compatibility level. The idea is that each compatibility level controls behavior that changed in that version of bash, but that behavior may have been present in earlier versions. For instance, the change to use locale-based comparisons with the [[ command came in bash-4.1, and earlier versions used ASCII-based comparisons, so enabling compat32 will enable ASCII-based comparisons as well. That granularity may not be sufficient for all uses, and as a result users should employ compatibility levels carefully. Read the documentation for a particular feature to find out the current behavior. ๐Ÿ‘€

Bash-4.3 introduced a new shell variable: BASH_COMPAT. The value assigned to this variable (a decimal version number like 4.2, or an integer corresponding to the compatNN option, like 42) determines the compatibility level.

Starting with bash-4.4, bash began deprecating older compatibility levels. Eventually, the options will be removed in favor of BASH_COMPAT. ๐Ÿ’€

Bash-5.0 was the final version for which there was an individual shopt option for the previous version. BASH_COMPAT is the only mechanism to control the compatibility level in versions newer than bash-5.0.

The following table describes the behavior changes controlled by each compatibility level setting. The compatNN tag is used as shorthand for setting the compatibility level to NN using one of the following mechanisms. For versions prior to bash-5.0, the compatibility level may be set using the corresponding compatNN shopt option. For bash-4.3 and later versions, the BASH_COMPAT variable is preferred, and it is required for bash-5.1 and later versions.

๐Ÿงš compat31

  • Quoting the rhs of the [[ command's regexp matching operator (=) has no special effect.

๐Ÿงš compat32

  • The < and > operators to the [[ command do not consider the current locale when comparing strings; they use ASCII ordering.

๐Ÿงš compat40

  • The < and > operators to the [[ command do not consider the current locale when comparing strings; they use ASCII ordering. Bash versions prior to bash-4.1 use ASCII collation and strcmp(3); bash-4.1 and later use the current locale's collation sequence and strcoll(3).

๐Ÿงš compat41

  • In posix mode, time may be followed by options and still be recognized as a reserved word (this is POSIX interpretation 267).
  • In posix mode, the parser requires that an even number of single quotes occur in the word portion of a double-quoted parameter expansion and treats them specially, so that characters within the single quotes are considered quoted (this is POSIX interpretation 221).

๐Ÿงš compat42

  • The replacement string in double-quoted pattern substitution does not undergo quote removal, as it does in versions after bash-4.2.
  • In posix mode, single quotes are considered special when expanding the word portion of a double-quoted parameter expansion and can be used to quote a closing brace or other special character (this is part of POSIX interpretation 221); in later versions, single quotes are not special within double-quoted word expansions.

๐Ÿงš compat43

  • Word expansion errors are considered non-fatal errors that cause the current command to fail, even in posix mode (the default behavior is to make them fatal errors that cause the shell to exit).
  • When executing a shell function, the loop state (while/until/etc.) is not reset, so break or continue in that function will break or continue loops in the calling context. Bash-4.4 and later reset the loop state to prevent this.

๐Ÿงš compat44

  • The shell sets up the values used by BASH_ARGV and BASH_ARGC so they can expand to the shell's positional parameters even if extended debugging mode is not enabled.
  • A subshell inherits loops from its parent context, so break or continue will cause the subshell to exit. Bash-5.0 and later reset the loop state to prevent the exit
  • Variable assignments preceding builtins like export and readonly that set attributes continue to affect variables with the same name in the calling environment even if the shell is not in posix mode.

๐Ÿงš compat50

  • Bash-5.1 changed the way $RANDOM is generated to introduce slightly more randomness. If the shell compatibility level is set to 50 or lower, it reverts to the method from bash-5.0 and previous versions, so seeding the random number generator by assigning a value to RANDOM will produce the same sequence as in bash-5.0.
  • If the command hash table is empty, bash versions prior to bash-5.1 printed an informational message to that effect, even when producing output that can be reused as input. Bash-5.1 suppresses that message when the -l option is supplied.

๐Ÿงš compat51

  • The unset builtin treats attempts to unset array subscripts @ and * differently depending on whether the array is indexed or associative, and differently than in previous versions.
  • Arithmetic commands ( ((...)) ) and the expressions in an arithmetic for statement can be expanded more than once.
  • Expressions used as arguments to arithmetic operators in the [[ conditional command can be expanded more than once.
  • The expressions in substring parameter brace expansion can be expanded more than once.
  • The expressions in the $((...)) word expansion can be expanded more than once.
  • Arithmetic expressions used as indexed array subscripts can be expanded more than once.
  • test -v, when given an argument of A[@], where A is an existing associative array, will return true if the array has any set elements. Bash-5.2 will look for and report on a key named @.
  • The ${parameter[:]=value} word expansion will return value, before any variable-specific transformations have been performed (e.g., converting to lowercase). Bash-5.2 will return the final value assigned to the variable.
  • Parsing command substitutions will behave as if extended globbing (see the description of the shopt builtin above) is enabled, so that parsing a command substitution containing an extglob pattern (say, as part of a shell function) will not fail. This assumes the intent is to enable extglob before the command is executed and word expansions are performed. It will fail at word expansion time if extglob hasn't been enabled by the time the command is executed.

๐Ÿงš compat52

  • The test builtin uses its historical algorithm to parse parenthesized subexpressions when given five or more arguments.
  • If the -p or -P option is supplied to the bind builtin, bind treats any arguments remaining after option processing as bindable command names, and displays any key sequences bound to those commands, instead of treating the arguments as key sequences to bind.

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

bash(1), sh(1)


and that's a wrap on the whole page, bestie ๐ŸŽ€ this was GNU Bash-2.05a, dated 2001 October 29 โ€” yes, she's vintage, she's an icon, she's been serving shell semantics since before some of us could read. go forth and wait responsibly. ๐Ÿ’–โœจ๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from