BASH_BUILTINS(1)
โจ BASH_BUILTINS(1) โจ
okay bestie, this is BASH_BUILTINS(1) from the General Commands Manual ๐ธ It's the page all about bash's built-in commands, and I am obsessed ๐ญ๐
๐ NAME ๐
The whole squad: :, ., [, alias, bg, bind, break, builtin, caller, cd, command, compgen, complete, compopt, continue, declare, dirs, disown, echo, enable, eval, exec, exit, export, false, fc, fg, getopts, hash, help, history, jobs, kill, let, local, logout, mapfile, popd, printf, pushd, pwd, read, readarray, readonly, return, set, shift, shopt, source, suspend, test, times, trap, true, type, typeset, ulimit, umask, unalias, unset, wait โ bash built-in commands, see bash(1) ๐ฆ
๐ BASH BUILTIN COMMANDS ๐
Okay so, unless otherwise noted, every builtin in this section that takes options with a - accepts -- to mean "the options are over" ๐ The :, true, false, and test/[ builtins don't take options at all and don't treat -- specially, so they're giving minimalist ๐ The exit, logout, return, break, continue, let, and shift builtins accept and process arguments that start with - without needing --. Any other builtin that takes arguments but isn't listed as taking options will read a - argument as an invalid option, so you need -- to stop that โ ๏ธ
๐ง :
: [arguments]
It literally does nothing ๐ It just expands the arguments and does any redirections you asked for. The return status is zero.
๐ฆ . and source
. [-p path] filename [arguments]
source [-p path] filename [arguments]
The . command (aka source) reads and executes commands from filename in the current shell environment, and returns the exit status of the last command it ran from filename โจ
If filename doesn't contain a slash, . goes searching for it ๐ If you pass -p, . treats path as a colon-separated list of directories to hunt through for filename. Otherwise it uses the entries in PATH to find the directory containing filename. filename doesn't need to be executable. When bash isn't in posix mode, it searches the current directory if filename isn't 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 you supply any arguments, they become the positional parameters when filename is executed. Otherwise the positional parameters stay unchanged.
If the -T option is enabled, . inherits any trap on DEBUG. If it isn't, any DEBUG trap string is saved and restored around the call to ., and . unsets the DEBUG trap while it runs. If -T isn't 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 you pass arguments, it defines an alias for each name that has a value given. A trailing space in value means the next word gets checked for alias substitution when the alias is expanded during command parsing, which is lowkey a power move ๐ฅ For each name in the argument list with no value supplied, it prints the name and value of the alias name. alias returns true unless a name is given (without a corresponding =value) that has no alias defined.
๐ bg
bg [jobspec ...]
Resumes each suspended job jobspec in the background, as if it had been started with & ๐โโ๏ธ If jobspec isn't present, the shell uses its notion of the current job. bg jobspec returns 0 unless it's run when job control is disabled or, when job control is 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
This one is a whole vibe ๐ It displays current readline key and function bindings, binds a key sequence to a readline function or macro or to a shell command, or sets a readline variable. Each non-option argument is a key binding or command the way it would look in a readline initialization file like .inputrc, but each binding or command has to be passed as a separate argument, e.g., \C-x\C-r: re-read-init-file. In the descriptions below, output that's 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, mean the following:
-m keymapโ Use keymap as the keymap affected by the subsequent bindings. Acceptable keymap names areemacs,emacs-standard,emacs-meta,emacs-ctlx,vi,vi-move,vi-command, andvi-insert.viis equivalent tovi-command(vi-moveis also a synonym), andemacsis equivalent toemacs-standard.-lโ List the names of all readline functions.-pโ Display readline function names and bindings in a way that can be used as an argument to a laterbindcommand or in a readline initialization file. If arguments remain after option processing,bindtreats 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,bindtreats 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 a way that can be used as an argument to a laterbindcommand 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 a way that can be used as an argument to a laterbindcommand 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. Here's how each one plays out:- With whitespace as the separator, shell-command must be enclosed in double quotes, and readline expands any of its special backslash-escapes in shell-command before saving it.
- With a colon as the separator, 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_LINEvariable to the contents of the readline line buffer, and theREADLINE_POINTandREADLINE_MARKvariables 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_ARGUMENTvariable. If there was no argument, that variable is not set. - If the executed command changes the value of any of
READLINE_LINE,READLINE_POINT, orREADLINE_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 laterbindcommand.
The return value is 0 unless an unrecognized option is supplied or an error occurred.
๐ฆ break
break [n]
Exits 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]
Runs the specified shell builtin shell-builtin, passing it arguments, and returns its exit status ๐ This is useful when you define a function with the same name as a shell builtin and still want the builtin's functionality inside that 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 you supply a non-negative integer as expr, caller displays the line number, subroutine name, and source file corresponding to that position in the current execution call stack. This extra info can 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
cd [-L] [-@] [dir]
cd -P [-e] [-@] [dir]
okay so cd is literally the move-me-somewhere command ๐ง it changes the current directory to dir. if you don't hand it a dir, it grabs whatever's in the HOME shell variable and takes you there ๐ the CDPATH thing is lowkey iconic: if the CDPATH variable exists and dir doesn't start with a slash (/), cd treats CDPATH as a search path and checks each directory in it for dir. multiple CDPATH entries are split by a colon (:) ๐ an empty entry in CDPATH counts as your current directory, i.e.,
the -P flag tells cd to use the physical directory structure ๐
it resolves symbolic links while it walks through dir, and it does that before dealing with any .. in dir (see also the -P option to the set builtin command).
the -L flag forces cd to follow symbolic links ๐ฆ it resolves the link after handling any .. in dir. when .. shows up, cd removes the immediately previous pathname component from dir, going back to a slash or the beginning of dir, and then double-checks that the part it has processed so far is still a valid directory name. if it isn't, cd returns a non-zero status ๐ if you don't pass -L or -P, cd acts like you passed -L.
if you use -e together with -P, and cd can't successfully figure out the current working directory after a directory change that worked, it returns a non-zero status ๐
on systems that support it, the -@ option shows the extended attributes of a file as if it were a directory โจ
an argument of - gets converted to $OLDPWD before cd tries the directory change ๐
ifcduses a non-empty directory name fromCDPATH, or-is the first argument, and the change works,cdprints the absolute pathname of the new working directory to the standard output. no cap, you'll want to know that one ๐
if the directory change is successful, cd sets the PWD environment variable to the new directory name, and sets the OLDPWD environment variable to whatever the current working directory was before the change ๐ธ
the return value is true if the directory got changed successfully, and false otherwise ๐
-Lโ follow symbolic links by resolving them after..gets processed (this is the default if neither-Lnor-Pis given) ๐ฆ-Pโ use the physical directory structure by resolving symbolic links before processing..๐-eโ only meaningful with-P; return a non-zero status if the current working directory can't be determined after a successful change ๐-@โ on supporting systems, present a file's extended attributes as a directory ๐ง
๐ธ command
command [-pVv] command [arg ...]
the command builtin runs command with args, and it skips the usual shell function lookup for command ๐
only builtin commands, or commands found in the PATH, get executed. it's giving main character energy โจ
-pโ the search for command uses a default value forPATHthat's guaranteed to find all the standard utilities ๐-Vโ print a more verbose description of command ๐-vโ print a single word showing the command or filename used to invoke command ๐ซถ
if you pass either -V or -v, command prints a description of command. -v gives you one word with the command or filename used to call it, while -V gives you the more detailed version ๐
if -V or -v is supplied, the exit status is zero when command was found, and non-zero if it wasn't ๐ if neither option is supplied and an error happened 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 ๐
๐ฆ compgen
compgen [-V varname] [option] [word]
compgen generates possible completion matches for word according to the options and writes the matches to the standard output ๐ง the options can be any option the complete builtin accepts, except -p, -r, -D, -E, and -I ๐
โโ๏ธ
-V varnameโ instead of printing the completions, store them in the indexed array variable varname ๐
if you pass -V, compgen stores the generated completions into the indexed array variable varname instead of writing them to the standard output ๐
when you use the-For-Coptions, the various shell variables set by the programmable completion facilities won't have useful values. they might be available, but they won't be useful, so don't rely on them ๐
the matches get generated the same way they would if the programmable completion code had produced them directly from a completion specification with the same flags ๐ฅ if word is specified, only the completions that match word get displayed or stored โจ
the return value is true unless an invalid option is supplied, or no matches were generated ๐
๐ complete
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 ...]
this is where you tell bash how the arguments to each name should get completed ๐ซถ it's the vibe-setter of the completion world ๐
if you pass -p, or if you pass no options and no names at all, complete prints the existing completion specifications in a way that you can feed right back in as input ๐ the -r option removes the completion specification for each name, or, if you don't supply any names, removes all of the completion specifications ๐งน
the -D option means your other options and actions should apply to command completion, so the completion attempted on a command that doesn't have any completion defined yet ๐ฏ the -E option means your other options and actions should apply to command completion too, but specifically the completion attempted on a blank line ๐ธ the -I option means they should apply to completion on the initial non-assignment word on the line, or after a command delimiter like ; or |, which is usually command name completion ๐ฆ
if you supply more than one of these, -D takes precedence over -E, and both of them take precedence over -I ๐ if you supply any of -D, -E, or -I, any other name arguments get ignored, because these completions only apply to the case the option is for ๐
the process of applying these completion specifications when attempting word completion is described in bash(1) ๐
other options, if you specify them, have the following meanings. heads up on the quoting ๐
the arguments to the-G,-W, and-Xoptions (and, if necessary, the-Pand-Soptions) should be quoted to protect them from expansion before thecompletebuiltin is invoked. no skipping this part, bestie, or the shell will expand them beforecompleteever sees them ๐ญ
-o comp-optionโ okay so this one tweaks how the compspec behaves beyond just spitting out completions ๐comp-optioncan be any of these:bashdefaultโ ๐ if the compspec comes back empty, run the rest of the usual bash completions.defaultโ ๐ธ if the compspec finds nothing, fall back to readline's default filename completion.dirnamesโ ๐ฆ if the compspec finds nothing, do directory name completion instead.filenamesโ ๐ tells readline the compspec is giving back filenames, so readline can do its filename magic (adding a slash to directories, quoting special characters, and suppressing trailing spaces). This one's meant for shell functions.fullquoteโ ๐ซถ tells readline to quote every completed word, even if it isn't a filename.noquoteโ ๐ tells readline not to quote completed words that are filenames. (Quoting filenames is the default, so this is the opt-out.)nosortโ ๐ tells readline not to sort the possible completions alphabetically.nospaceโ โจ tells readline not to add a space (the default) after words completed at the end of the line.plusdirsโ ๐ after the compspec makes its matches, it also tries directory name completion and tosses those matches into the results of the other actions.
-A actionโ ๐ the action can be one of these to generate your 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, kinda like 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 thehelpbuiltin.hostnameโ hostnames, pulled from the file named in theHOSTFILEshell 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-ooption to thesetbuiltin.shoptโ shell option names, as accepted by theshoptbuiltin.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 run in a subshell environment, and whatever it outputs becomes the possible completions. Arguments get passed the same way as with-F.-F functionโ โญ the shell function function runs in the current shell environment. When it runs,$1is the name of the command whose arguments are being completed,$2is the word being completed, and$3is the word right before the word being completed on the current command line. Once the function finishes, programmable completion grabs the possible completions from the value of theCOMPREPLYarray variable.-G globpatโ ๐ฆ expands the pathname expansion pattern globpat to generate the possible completions.-P prefixโ ๐ธ adds prefix to the start of each possible completion, after all the other options have been applied.-S suffixโ ๐ appends suffix to each possible completion, after all the other options have been applied.-W wordlistโ ๐ splits wordlist using the characters in theIFSspecial variable as delimiters, then expands each resulting word. Shell quoting is honored inside wordlist, so words can contain shell metacharacters or characters from the value ofIFS. The possible completions are the members of the result that match a prefix of the word being completed.-X filterpatโ ๐ filterpat is a pattern, just like the ones used for pathname expansion. It gets applied to the list of possible completions made by the earlier options and arguments, and any completion that matches filterpat gets removed. A leading!in filterpat flips it, so any completion that does not match gets removed instead.
The return value is true unless an invalid option is supplied, an option other than -p, -r, -D, -E, or -I is supplied without a name argument, an attempt is made to remove a completion specification for a name that has no specification, or 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 no options are supplied, it displays the completion options for each name or for the current completion. The possible values of option are the ones that are valid for the complete builtin described above. โจ
The -D option says the other supplied options should apply to command completion. The -E option says the other supplied options should apply to command completion too. The -I option says the other supplied options should apply to completion on the initial word on the line. These get determined the same way as they do for the complete builtin. ๐
If you supply multiple options, -D takes precedence over -E, and both of those take precedence over -I. ๐
The return value is true unless an invalid option is supplied, an attempt is made to modify the options for a name that has no completion specification, or 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). The return value is 0 unless n is not greater than or equal to 1. ๐ฆ
๐ฅ declare / typeset
declare [-aAfFgiIlnrtux] [-p] [name[=value] ...]
typeset [-aAfFgiIlnrtux] [-p] [name[=value] ...]
Declare variables and/or give them attributes. If no names are given, 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, additional options, other than -f and -F, are ignored. ๐
When -p is supplied without name arguments, declare displays the attributes and values of all variables that have the attributes specified by the additional options. If no other options are supplied with -p, declare displays the attributes and values of all shell variables. The -f option restricts the display to shell functions. ๐ง
The -F option stops the display of function definitions, so only the function name and its 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. โญ
The -g option forces variables to be created or modified at the global scope, even when declare is run inside a shell function. It's ignored when declare isn't run inside a shell function. ๐
The -I option makes local variables 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 unset. ๐ซถ
The following options let you filter output down to variables with a specific attribute, or give variables attributes ๐
-aโ each name becomes an indexed array variable (see Arrays in bash(1)) ๐ธ-Aโ each name becomes 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, so arithmetic evaluation (see ARITHMETIC EVALUATION in bash(1)) happens whenever you assign it a value ๐ฅ-lโ when you assign a value, every upper-case character gets converted to lower-case. This also disables the upper-case attribute ๐-nโ gives each name the nameref attribute, making it a name reference to another variable. That other variable is whichever one the value of name points to. Every reference, assignment, and attribute change to name gets performed on the referenced variable instead, except the ones that use or change the-nattribute itself. The nameref attribute can't be applied to array variables ๐-rโ makes names readonly. Subsequent assignment statements can't give them values, and they can't be unset either ๐-tโ gives each name the trace attribute. Traced functions inherit theDEBUGandRETURNtraps from the calling shell. For variables, the trace attribute doesn't mean anything special โจ-uโ when you assign a value, every lower-case character gets converted to upper-case. This disables the lower-case attribute ๐-xโ marks each name for export to subsequent commands through the environment ๐
Using + instead of - turns off the specified attribute instead. The exceptions are that +a and +A can't be used to destroy array variables, and +r won't remove the readonly attribute ๐
When you use declare or typeset inside a function, each name becomes local, just like with the local command, unless you pass the -g option ๐ If a variable name is followed by =value, the variable gets set to that value. When you use -a or -A with the compound assignment syntax to create array variables, the extra attributes don't take effect until later assignments ๐ซถ
The return value is 0 unless one of these happens, and then it's not 0 ๐ญ:
- 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 (the original page repeats this bit, not me ๐)
- 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
- an attempt is made to display a non-existent function with
-f
๐บ๏ธ dirs
dirs [-clpv] [+n] [-n]
Without options, dirs shows you the list of directories it's currently remembering, on a single line with the names separated by spaces. Directories get added to the list with the pushd command, and the popd command removes entries from it. The current directory is always the first directory in the stack ๐งญ
Here's what the options do, if you supply them:
-cโ clears the directory stack by deleting all of the entries ๐งน-lโ produces a listing with full pathnames. The default listing format uses a tilde to stand in for the home directory ๐-pโ prints the directory stack with one entry per line ๐-vโ prints the directory stack with one entry per line, and puts each entry's index in the stack in front of it ๐ข+nโ displays the nth entry counting from the left of the list thatdirsshows when you run it without options. Counting starts at zero ๐-nโ displays the nth entry counting from the right of that same list. Counting starts at zero too ๐
The return value is 0 unless you use an invalid option, or n goes past the end of the directory stack ๐
๐ disown
disown [-ar] [-h] [id ...]
Without options, disown removes each id from the table of active jobs. Each id can be a job specification, jobspec, or a process ID, pid. If the id is a pid, disown uses the job that contains that pid as the jobspec ๐ฏ
If you supply the -h option, disown doesn't remove the jobs for each id from the jobs table. Instead, it marks them so the shell won't send SIGHUP to the job when the shell gets a SIGHUP ๐ก๏ธ
If you don't supply an id, the -a option means to remove or mark all jobs. The -r option without an id argument removes or marks running jobs. If you don't supply an id, and you don't use -a or -r either, disown removes or marks the current job ๐
The return value is 0 unless an id doesn't specify a valid job ๐ธ
๐ echo
echo [-neE] [arg ...]
echo outputs the args, separated by spaces, and then a newline. The return status is 0 unless a write error happens. If you use -n, the trailing newline doesn't get printed ๐ข
If you give the -e option, echo interprets the backslash-escaped characters listed below. The -E option turns that interpretation off, even on systems where the escapes are interpreted by default. The xpg_echo shell option decides whether echo interprets any options and expands these escape characters. And echo does not treat -- as the end of options, so no special meaning there ๐
echo understands these escape sequences:
\aโ alert (bell) ๐\bโ backspace โฌ ๏ธ\cโ suppresses 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 valuennn(zero to three octal digits) ๐\xHHโ the eight-bit character whose value is the hexadecimal valueHH(one or two hex digits) ๐ค\uHHHHโ the Unicode (ISO/IEC 10646) character whose value is the hexadecimal valueHHHH(one to four hex digits) ๐\UHHHHHHHHโ the Unicode (ISO/IEC 10646) character whose value is the hexadecimal valueHHHHHHHH(one to eight hex digits) ๐
Any unrecognized backslash-escaped characters that echo comes across get written out unchanged ๐ซ
๐ enable
enable [-a] [-dnps] [-f filename] [name ...]
enable turns builtin shell commands on and off. Disabling a builtin lets an executable file with the same name as a shell builtin get run without typing a full pathname, even though the shell normally looks for builtins before files ๐ต๏ธ
If you use -n, each name gets disabled. Otherwise, the names get enabled. For example, to use the test binary found through PATH instead of the shell builtin version, run
If you don't supply any name arguments, or you supply the -p option, enable prints a list of shell builtins. With no other option arguments, the list has all enabled shell builtins. If you use -n, it prints only disabled builtins. If you use -a, the list includes all builtins, with an indication of whether each one is enabled. The -s option restricts the output to the POSIX special builtins ๐
The -f option loads the new builtin command name from shared object filename, on systems that support dynamic loading. If filename doesn't contain a slash, Bash uses the value of the BASH_LOADABLES_PATH variable as a colon-separated list of directories to search for filename. The default for BASH_LOADABLES_PATH is system-dependent, and it may include . to force a search of the current directory ๐ The -d option deletes a builtin you previously loaded with -f. If you use -s with -f, the new builtin becomes a POSIX special builtin ๐งฉ
If you don't supply any options and name isn't a shell builtin, enable will try to load name from a shared object named name, as if the command were
The return value is 0 unless a name isn't a shell builtin, or there's an error loading a new builtin from a shared object ๐
The page cuts off right at those "run" and "as if the command were" bits, bestie, so I'm not making up the rest ๐
๐ฝ๏ธ eval
eval [arg ...]
eval concatenates the args together into a single command, separated by spaces. Bash then reads and executes this command, and eval returns its exit status as its own return status. If there are no args, or only null arguments, eval returns 0 ๐ง
๐ exec
exec [-cl] [-a name] [command [arguments]]
If you specify command, it replaces the shell without creating a new process. command can't be a shell builtin or function. The arguments become the arguments to command ๐โโ๏ธ If you use the -l option, the shell puts a dash at the beginning of the zeroth argument passed to command. This is what login(1) does ๐
The -c option makes command run with an empty environment ๐ซง If you use -a, the shell passes name as the zeroth argument to the executed command ๐ชช
If command can't 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 can't be executed. A subshell exits unconditionally if exec fails ๐ฌ
If you don't specify command, any redirections take effect in the current shell, and the return status is 0. If there's a redirection error, the return status is 1 ๐
๐ช exit
exit [n]
exit makes the shell exit with a status of n. If you omit n, the exit status is whatever the last command executed had. Any trap on EXIT gets executed before the shell terminates ๐
๐ค export
export [-fn] [name[=value]] ...
export -p [-f]
The names you supply get marked for automatic export to the environment of commands run afterwards. If you give the -f option, the names refer to functions ๐
Okay so -n is the unexport button ๐
โโ๏ธ. It strips the export attribute off each name you give it ๐
. If you don't pass any names, or you only pass -p, export lists every exported variable name on stdout โจ. Add -f alongside -p and it shows the exported functions instead ๐ง. And -p prints its output in a format you can paste straight back in as input ๐ซถ.
export also lets you set a value while exporting or unexporting, by tacking =value onto the name ๐. The variable gets that value and the export attribute changes. Iconic.
export returns 0 unless one of these happens ๐: you pass an invalid option, one of the names isn't a valid shell variable name, or you use -f with a name that isn't a function.
๐ฆ false
Literally does nothing ๐ญ and returns a non-zero status. Pure background character energy.
๐ธ fc
fc [-e ename] [-lnr] [first] [last]
fc -s [pat=rep] [cmd]
The first form grabs a range of commands from the history list, from first to last, and lets you display or edit and re-execute them ๐. first and last can be a string (it finds the last command starting with that string) or a number (an index into the history list, where a negative number counts back from the current command number) ๐ข.
When you're listing, a first or last of 0 acts like -1, and -0 means the current command (usually the fc command itself) ๐คฏ. Otherwise 0 acts like -1, and -0 is invalid ๐ซ. If last isn't given, it defaults to the current command for listing (so it prints the last 10 commands) and to first otherwise. If first isn't given, it defaults to the previous command for editing and -16 for listing.
-lโ lists the commands on stdout ๐-nโ hides the command numbers when listing ๐-rโ flips the order of the commands ๐
If you don't use -l, fc opens an editor named by ename on a file full of those commands โ๏ธ. No ename? It checks FCEDIT, then EDITOR if FCEDIT isn't set, and if neither is set it goes with vi ๐
. Once you're done editing, fc reads the file back, echoes the commands, and runs them ๐.
The second form re-runs command after swapping every instance of pat for rep ๐ช. command gets interpreted the same way as first above.
A super useful alias to pair with fc is one that makes typing runs the last command beginning with and typing re-executes the last command ๐ง.
For the first form, the return value is 0 unless you pass an invalid option or first or last point to history lines that are out of range ๐ซ . When you're editing and re-running a file of commands, the return value is the value of the last command run, or failure if something goes wrong with the temporary file. For the second form, the status is whatever the re-run command returned, unless cmd doesn't match a valid history entry, in which case fc returns a non-zero status.
๐ฅ fg
fg [jobspec]
Brings jobspec back to the foreground and makes it the current job ๐โโ๏ธ. No jobspec? fg uses the shell's idea of the current job. The return value is whatever the command that moved to the foreground returned. You get failure if you run it with job control disabled, or with job control enabled when jobspec isn't a valid job, or when jobspec is a job that was started without job control ๐ค.
๐ง getopts
getopts optstring name [arg ...]
getopts is for shell scripts and functions that want to parse positional parameters and grab options and their arguments ๐. optstring holds the option characters it should recognize. If a character is followed by a colon, that option is expected to have an argument, which has to be separated from it by whitespace. Colon and question mark can't be option characters, so don't even try ๐
โโ๏ธ.
Every time it runs, getopts puts the next option into the shell variable name (creating name if it doesn't exist yet) and the index of the next argument to process into OPTIND โจ. OPTIND starts at 1 every time the shell or a shell script is invoked. If an option needs an argument, getopts puts that argument into OPTARG ๐.
Heads up ๐: the shell does not reset OPTIND for you. If you call getopts more than once in the same shell invocation to use a new set of parameters, you have to reset it yourself.
When getopts runs out of options, it exits with a return value greater than zero ๐. OPTIND gets set to the index of the first non-option argument, and name gets set to ?.
Normally getopts parses the positional parameters, but if you supply arg values, it parses those instead ๐ซถ.
For error reporting, there are two modes. If the first character of optstring is a colon, getopts goes silent. Otherwise it prints diagnostic messages when it hits invalid options or missing option arguments ๐ฃ. If OPTERR is set to 0, getopts won't display any error messages, even if the first character of optstring isn't a colon ๐คซ.
- Invalid option โ
getoptsputs?intonameand, if it's not silent, prints an error message and unsetsOPTARG. If it is silent, it stores the option character it found inOPTARGand skips the diagnostic ๐ค. - Missing required argument โ if it's not silent,
namebecomes a question mark (?),OPTARGgets unset, and a diagnostic message prints. If it is silent,namebecomes a colon (:) andOPTARGgets the option character it found ๐ญ.
getopts returns true if it finds an option, whether or not that option was specified in optstring. It returns false if it reaches the end of the options or an error happens ๐
.
๐ hash
hash [-lr] [-p filename] [-dt] [name]
Every time you call hash, it remembers the full pathname of the command name, figured out by searching the directories in $PATH ๐บ๏ธ. Any pathname that was already remembered for name gets tossed. If you pass -p, hash uses filename as the full pathname of the command instead ๐ฆ.
-rโ makes the shell forget all remembered locations. Assigning to thePATHvariable also clears all hashed filenames ๐งน.-dโ makes the shell forget the remembered location of eachname๐.-tโ prints the full pathname for eachname. If you pass multiplenamearguments with-t, it prints the name before its hashed full pathname ๐ท๏ธ.-lโ displays the output in a format you can reuse as input ๐ซถ.
With no arguments, or with only -l, hash prints info about the remembered commands ๐. The -t, -d, and -p options (the ones that act on the name arguments) are mutually exclusive, so only one will be active. If you supply more than one, -t beats -p, and both beat -d ๐.
The return status is zero unless a name isn't found or you pass an invalid option ๐ซ .
๐ help
help [-dms] [pattern]
help shows you helpful info about builtin commands ๐. If you give it a pattern, you get detailed help on every command matching that pattern, as described below. Without a pattern, it lists all the builtins and shell compound commands ๐.
Options, if you use them, mean:
-dโ displays a short description of each pattern-mโ displays the description of each pattern in a manpage-like format ๐-sโ displays only a short usage synopsis for each pattern โก
If pattern has pattern matching characters (see Pattern Matching above), it's treated as a shell pattern, and help prints the description of each help topic that matches ๐. If it doesn't have them, but pattern exactly matches the name of a help topic, help prints that topic's description ๐ฏ. Otherwise help does 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, history displays 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 for each history entry โฐ. When history uses HISTTIMEFORMAT, it doesn't print an intervening space between the formatted time stamp and the history entry ๐
.
If you supply filename, history uses it as the name of the history file. If you don't, it uses the value of HISTFILE ๐. And here's the tea โ: if filename isn't supplied and HISTFILE is unset or null, the -a, -n, -r, and -w options have no effect ๐.
Okay so the history options are where it gets spicy ๐ฅ Here's the whole lineup:
-cโ ๐งน Clear the history list by deleting all the entries. You can pair this with the other options to replace the history list.-d offsetโ ๐๏ธ Delete the history entry at position offset. If offset is negative, it's counted relative to one greater than the last history position, so negative indices count back from the end of the history. An index of-1refers to the current history-dcommand.-d start-endโ โ๏ธ Delete the range of history entries between positions start and end, inclusive. Positive and negative values for start and end work the way I just described.-aโ ๐ค Append the history lines to the history file. These are lines entered since the start of the current bash session that haven't been appended to the history file yet.-nโ ๐ฅ Read the history lines that haven't been read from the history file yet and add them to the current history list. These are lines appended to the history file since the start of the current bash session.-rโ ๐ Read the history file and append its contents to the current history list.-wโ ๐พ Write the current history list to the history file, overwriting the history file.-pโ ๐ Perform history substitution on the following args and display the result on standard output, without storing the results in the history list. Each arg must be quoted to disable normal history expansion.-sโ ๐งท Store the args in the history list as a single entry. The last command in the history list is removed before the args get added.
If the HISTTIMEFORMAT variable is set, history writes the time stamp info for each entry into the history file, marked with the history comment character. When the history file gets read, lines that start with the history comment character and are immediately followed by a digit get treated as timestamps for the next history entry. โฐโจ
The return value is 0 unless an invalid option is encountered, an error happens while reading or writing the history file, an invalid offset or range gets passed to -d, or the history expansion passed to -p fails. ๐ฆ
jobs ๐ผ
jobs [-lnprs] [ jobspec ... ]
jobs -x command [ args ... ]
The first form lists the active jobs, and these options get you the details:
-lโ ๐ List process IDs along with the normal info.-nโ ๐ Show info only for jobs whose status has changed since you were last notified about 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 you pass a jobspec, jobs narrows the output down to info about that one job. The return status is 0 unless an invalid option is encountered or an invalid jobspec is supplied. ๐
If you use the -x option, jobs swaps any jobspec found in command or args for the matching process group ID, then runs command with args passed to it, and returns its exit status. ๐
kill ๐ฅ
kill [-s sigspec | -n signum | -sigspec] id [ ... ]
kill -l|-L [sigspec | exit_status]
kill sends the signal named by sigspec or signum to each id. Each id can be a job specification jobspec or a process ID pid. sigspec is either a case-insensitive signal name like SIGKILL (with or without the SIG prefix) or a signal number, and signum is a signal number. If you don't supply a sigspec, kill sends SIGTERM. ๐ซถ
The -l option lists the signal names. If you give any arguments along with -l, kill lists the names of the signals that match those arguments, and the return status is 0. The exit_status argument to -l is a number that's either a signal number or the exit status of a process that got terminated by a signal. If you supply it, kill prints the name of the signal that made the process terminate. kill assumes process exit statuses are greater than 128, so anything less than that is treated as a signal number. The -L option is the same as -l. ๐
kill returns true if at least one signal was sent successfully, or false if an error happens or an invalid option is encountered. ๐
let ๐งฎ
let arg [arg ...]
Each arg gets 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. ๐ข
local ๐
local [option] [name[=value] ... | - ]
For each argument, local creates a local variable named name and assigns it value. The option can be any of the options that declare accepts. When you use local inside a function, the variable name only has a visible scope restricted to that function and its children. Using local outside of a function is an error. ๐ซ
If name is -, it makes the set of shell options local to the function where local gets invoked. Any shell options changed with the set builtin inside the function after the call to local get restored to their original values when the function returns. The restore happens as if a series of set commands ran to bring back the values that were in place before the function. โจ
With no operands, local writes a list of local variables to 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 ๐
logout [n]
Exits a login shell and returns a status of n to the shell's parent. ๐ฆ
mapfile ๐บ๏ธ
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]
mapfile reads lines from standard input, or from file descriptor fd if you use the -u option, into the indexed array variable array. The variable MAPFILE is the default array. Here's what the options do:
-d delimโ ๐ช Use the first character of delim to end each input line, instead of newline. If delim is the empty string,mapfileends a line when it reads a NUL character.-n countโ ๐ข Copy at most count lines. If count is0, copy all lines.-O originโ ๐ Begin assigning to array at index origin. The default index is0.-s countโ ๐๏ธ Discard the first count lines read.-tโ โ๏ธ Remove a trailing delim (default newline) from each line read.-u fdโ ๐ Read lines from file descriptor fd instead of standard input.-C callbackโ ๐ Evaluate callback each time quantum lines are read. The-coption specifies quantum.-c quantumโ ๐ 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 gets the index of the next array element to be assigned and the line to be assigned to that element as extra arguments. callback is evaluated after the line is read but before the array element is assigned. ๐ง
If you don't supply an explicit origin, mapfile clears array before assigning to it. ๐งน
mapfile returns zero unless an invalid option or option argument is supplied, array is invalid or unassignable, or array is not an indexed array. ๐
popd ๐
popd [-n] [+n] [-n]
popd removes entries from the directory stack. The elements are numbered starting from 0 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. If you supply arguments, they mean the following:
-nโ ๐ โโ๏ธ Suppress the normal change of directory when removing directories from the stack, so you only manipulate the stack.+nโ โฌ ๏ธ Remove the *n*th entry counting from the left of the list shown bydirs, 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 bydirs, 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 wasn't 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 succeeds, bash runs dirs to show the final contents of the directory stack, and the return status is 0. ๐ธ
printf ๐จ๏ธ
printf [-v var] format [arguments]
printf writes the formatted arguments to standard output, under the control of format. The -v option assigns the output to the variable var instead of printing it to standard output. ๐
The format string is where the magic lives, bestie ๐
It's made of three kinds of stuff: plain characters, which get copied straight to standard output, character escape sequences, which get converted and then copied, and format specifications, where each one grabs the next argument in line and prints it. On top of the standard printf(3) format characters cCsSndiouxXeEfFgGaA, bash's printf has some extra specifiers that are honestly iconic โจ
%bโ causes printf to expand backslash escape sequences in the corresponding argument, the same wayecho -edoes. ๐ธ%qโ outputs the corresponding argument in a format you can reuse as shell input ๐ซถ%qand%Quse$quoting if any characters in the argument need it, and backslash quoting otherwise. If the format string uses the printf alternate form, these two wrap the argument in single quotes instead.%Qโ like%q, but it applies any supplied precision to the argument before quoting it. Main character energy ๐%(datefmt)Tโ causes printf to output the date-time string you get from using datefmt as a format string for strftime(3) ๐ฆ The argument is an integer counting seconds since the epoch. This one has two special argument values:-1means the current time, and-2means the time the shell was invoked. If no argument is given, it acts like you passed-1. This is an exception to the usual printf behavior, so it's a little different and we love that for it ๐ง
The %b, %q, and %T specifiers all use the field width and precision arguments from the format specification. They write that many bytes from the expanded argument, or use that wide a field for it, and the expanded argument usually has more characters than the original ๐
The %n specifier takes a corresponding argument that gets treated as a shell variable name ๐
The %s and %c specifiers accept an l (long) modifier ๐ That forces them to convert the argument string to a wide-character string, and the field width and precision then count in characters, not bytes. %S and %C are just the same as %ls and %lc โจ
Arguments to non-string format specifiers are treated as C constants. 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 character right after it, using the current locale ๐
The format gets reused as many times as needed to eat all the arguments. If the format wants more arguments than you supplied, the extra specifications act like they got a zero value or a null string, whichever fits. The return value is zero on success, and non-zero if an invalid option is supplied or a write or assignment error happens ๐ญ
โจ pushd โจ
pushd [-n] [+n] [-n]
pushd [-n] [dir]
Okay so pushd adds a directory to the top of the directory stack, or rotates the stack so the new top becomes the current working directory ๐ฆ With no arguments, it swaps the top two elements of the stack. Here's what the arguments do:
-nโ suppresses the normal change of directory when you rotate or add directories, so it only manipulates the stack ๐+nโ rotates the stack so the *n*th directory is at the top. You count from the left of the list thatdirsshows, starting at zero ๐-nโ rotates the stack so the *n*th directory is at the top, but this time you count from the right of thedirslist, starting at zero ๐ธdirโ adds dir to the top of the directory stack ๐ซถ
After the stack gets modified, if -n wasn't supplied, pushd uses the cd builtin to switch to whatever directory is at the top. If the cd fails, pushd returns a non-zero value ๐
If no arguments are supplied, pushd returns zero unless the directory stack is empty. When rotating the stack, it returns zero unless the stack is empty or n points to a directory stack element that doesn't exist ๐
If pushd succeeds, bash runs dirs to show you the final contents of the directory stack โจ
โจ pwd โจ
pwd [-LP]
pwd prints the absolute pathname of your current working directory ๐ง The path it prints has no symbolic links if you use -P, or if the -o physical option to the set builtin is enabled. If you use -L, the printed path may contain symbolic links ๐ฆ The return status is 0 unless there's an error 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 is so good at splitting things up ๐ฅ It reads one line from standard input, or from the file descriptor fd you give to the -u option, and splits it into words the way bash (1) describes under Word Splitting. Then it assigns 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 leftover words and their in-between delimiters all get assigned to the last name. If fewer words are read than there are names, the remaining names get empty values ๐ญ The characters in the value of the IFS variable are what 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 from the next character read, and it's also used for line continuation ๐
Options, if you want them, do the following:
-a anameโ the words get assigned to sequential indices of the array variable aname, starting at 0. aname is unset before any new values are assigned. Any other name arguments get ignored ๐-d delimโ the first character of delim ends the input line instead of newline. If delim is the empty string,readends a line when it reads a NUL character ๐-eโ if standard input is coming from a terminal,readuses readline (see READLINE in bash(1)) to get the line. Readline uses the current editing settings (or the default ones, if line editing wasn't active before), but it uses readline's default filename completion ๐-Eโ same deal as-eif input is coming from a terminal, with readline and the current or default editing settings. The difference is that this one uses bash's default completion, including programmable completion ๐-i textโ if readline is being used to read the line,readputs text into the editing buffer before editing begins ๐ฆ-n ncharsโreadreturns after reading nchars characters instead of waiting for a complete line ๐ซถ It still returns early on EOF or a timeout. It does honor a delimiter if it hits one before reading nchars characters ๐ธ-N ncharsโreadreturns after reading exactly nchars characters, again instead of waiting for a full line, unless it hits EOF or times out. Delimiter characters in the input aren't treated specially, so they don't makereadreturn until it has read nchars characters. The result isn't split on the characters inIFS, because the goal is for the variable to get exactly the characters read (except for backslash, see the-roption below) โจ-p promptโ displays prompt on standard error, without a trailing newline, before trying to read any input. This only happens if input is coming from a terminal ๐-rโ backslash stops acting as an escape character. It's treated as part of the line. Because of that, a backslash-newline pair can't be used for line continuation ๐-sโ silent mode ๐ If input is coming from a terminal, characters don't get echoed.-t timeoutโ makesreadtime out and return failure if it doesn't read a complete line (or a specified number of characters) within timeout seconds โณ timeout can be a decimal number with a fractional part after the decimal point. This option only works ifreadis reading from a terminal, pipe, or other special file. It has no effect on regular files. Ifreadtimes out, it saves any partial input into the specified variable name, and the exit status is greater than128. If timeout is0,readreturns immediately without trying to read any data. In that case the exit status is0if input is available on the specified file descriptor, or non-zero ifreadwould return EOF ๐ง-u fdโ reads input from file descriptor fd instead of standard input ๐
Other than when delim is the empty string, read ignores any NUL characters in the input ๐ซถ
If you don't supply any names, read assigns the line it read to the variable REPLY. The line doesn't include the ending delimiter, but otherwise it's unmodified โจ
The exit status is zero, unless one of these happens: end-of-file is encountered, read times out (in which case the status is greater than 128), a variable assignment error occurs (like assigning to a readonly variable), or an invalid file descriptor is supplied as the argument to -u ๐ญ
๐ readonly
readonly [-aAf] [-p] [name[=word] ...]
Bestie, readonly is the bodyguard for your variables ๐ก๏ธ The names you give it become read-only, so later assignments or unset can't change their values. Iconic. ๐
If you add -f, each name refers to a shell function instead of a variable โจ
-aโ restricts the variables to indexed arrays ๐งบ-Aโ restricts the variables to associative arrays ๐๏ธ If you pass both-aand-A,-Awins ๐
If you don't give any names, or you pass -p, readonly prints a list of every readonly name ๐ The other options can narrow that list down to a subset of the readonly names. The -p output is formatted so you can feed it right back in as input ๐
You can also set a value at the exact same time you lock it by writing name=value ๐ That sets the variable to value and flips on the readonly attribute in one move. No cap, that's efficient.
The exit status is 0 unless one of these happens ๐: you hit an invalid option, one of the names isn't a valid shell variable name, or you use -f with a name that isn't a function.
โฉ๏ธ return
return [n]
return ends a shell function or a sourced file and hands the value of n back to whoever called it ๐ฆ If you leave n out, the status is whatever the last command that ran returned.
If return runs inside a trap handler, the status comes from the last command that ran before the trap handler kicked in ๐ชค Same vibe during a DEBUG trap, except the status comes from the last command the trap handler ran before return was invoked.
When you return from a script run with . (source), the shell stops that script and uses either n or the exit status of the last command inside the script as the script's exit status ๐ธ If you supply n, only its least significant 8 bits count.
Anything hooked up to the RETURN trap runs before execution picks back up after the function or script ๐ฅ
Heads up ๐ญ: the status is non-zero if you hand return a non-numeric argument, or if you use it outside a function without running inside a script sourced by . or source.
โ๏ธ set
set [-abefhkmnptuvxBCEHPT] [-o option-name] [--] [-] [arg ...]
set [+abefhkmnptuvxBCEHPT] [+o option-name] [--] [-] [arg ...]
set -o
set +o
Without options, set shows the name and value of every shell variable in a format you can paste back in to set or reset the variables that are currently set ๐ง Read-only variables can't be reset. In posix mode, only shell variables get listed. The output is sorted according to the current locale ๐
When you give options, they turn shell attributes on or off โญ Any arguments left over after option processing become the positional parameters, assigned in order to $1, $2, ..., $n ๐ง Here's what the options do:
-aโ every variable or function that gets created or modified is given the export attribute and marked for export to the environment of later commands ๐ค-bโ reports the status of terminated background jobs right away, instead of before the next primary prompt or after a foreground command ends ๐น๏ธ This only works when job control is enabled.-eโ exits immediately if a pipeline (which can be just one simple command), a list, or a compound command (see SHELL GRAMMAR inbash(1)) exits with a non-zero status ๐ช Bestie, the shell does not bail in these situations:- the failing command is in the list right after a
whileoruntilreserved word - it's part of the test after
iforelif - it's part of any command in a
&&or||list, except the command after the final&&or|| - it's any command in a pipeline except the last one (this depends on the
pipefailshell option) - the command's return value is being inverted with
!
- the failing command is in the list right after a
If a compound command other than a subshell returns non-zero because a command failed while -e was being ignored, the shell doesn't exit either ๐ซถ A trap on ERR, if set, runs before the shell exits. This option applies to the shell environment and each subshell environment separately (see COMMAND EXECUTION ENVIRONMENT in bash(1)), and it may cause subshells to exit before running all of their commands ๐ญ
Okay so, if a compound command or shell function runs in a context where -e is being ignored, none of the commands inside that compound command or function body get affected 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 running in a context where -e is ignored, that setting won't do anything until the compound command or the command containing the function call completes ๐.
-fโ Disable pathname expansion ๐ โโ๏ธ-hโ Remember where commands live as they get looked up for execution. This is on by default ๐ง-kโ Every argument written as an assignment gets placed in the environment for a command, not just the ones that come before the command name ๐-mโ Monitor mode, which means job control is on ๐. It's on by default for interactive shells on systems that support it (see JOB CONTROL inbash(1)). Every process runs in its own separate process group. When a background job finishes, the shell prints a line with its exit status โจ-nโ Reads commands but doesn't run them. This is a lowkey perfect way to check a shell script for syntax errors ๐. Interactive shells ignore it ๐-o option-nameโ The option-name can be one of these ๐ซถ:allexportโ Same as-a.braceexpandโ Same as-B.emacsโ Uses an emacs-style command line editing interface ๐ธ. It's on by default when the shell is interactive, unless the shell was started with the--noeditingoption. This also affects the editing interface used forread -e.errexitโ Same as-e.errtraceโ Same as-E.functraceโ Same as-T.hashallโ Same as-h.histexpandโ Same as-H.historyโ Enables command history, as described inbash(1)under HISTORY. It's on by default in interactive shells ๐.ignoreeofโ The effect is as if the shell command had been executed (see Shell Variables inbash(1)).keywordโ Same as-k.monitorโ Same as-m.noclobberโ Same as-C.noexecโ Same as-n.noglobโ Same as-f.nologโ Currently ignored ๐.notifyโ Same as-b.nounsetโ Same as-u.onecmdโ Same as-t.physicalโ Same as-P.pipefailโ If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if every command in the pipeline exits successfully ๐ฅ. This one's disabled by default.posixโ Enables posix mode, which changes bash's behavior wherever the default differs from the POSIX standard so it matches the standard ๐. See SEE ALSO inbash(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โ Uses a vi-style command line editing interface ๐ฆ. This also affects the editing interface used forread -e.xtraceโ Same as-x.
If -o is supplied with no option-name, set prints the current shell option settings. If +o is supplied with no option-name, set prints a series of set commands that recreate the current option settings on the standard output ๐งพ.
-pโ Turns on privileged mode ๐. In this mode, the shell doesn't read the$ENVand$BASH_ENVfiles, shell functions aren't inherited from the environment, and theSHELLOPTS,BASHOPTS,CDPATH, andGLOBIGNOREvariables are ignored if they show up in the environment. If the shell starts with an effective user (group) id that doesn't equal the real user (group) id, and-pisn't supplied, all of these actions happen and the effective user id gets set to the real user id. If-pis supplied at startup, the effective user id is not reset. Turning this option off sets the effective user and group ids to the real user and group ids.-rโ Enables restricted shell mode ๐ง. Once it's set, you cannot unset it ๐ญ.-tโ Exits after reading and executing one command ๐.-uโ Treats unset variables and parameters as an error during parameter expansion, with the exception of the special parameters@and*and array variables subscripted with@or*๐จ. If an expansion is attempted on an unset variable or parameter, the shell prints an error message and, if it isn't interactive, exits with a non-zero status.-vโ Prints shell input lines as they're read ๐.-xโ After expanding each simple command,forcommand,casecommand,selectcommand, or arithmeticforcommand, it displays the expanded value ofPS4, followed by the command and its expanded arguments or associated word list, to the standard error ๐ต๏ธโโ๏ธ.-Bโ The shell does brace expansion (see Brace Expansion inbash(1)) ๐. This is on by default.-Cโ If set, bash won't overwrite an existing file with the>,>&, and<>redirection operators ๐ก๏ธ. Using the>|redirection operator instead of>overrides this and forces the creation of an output file.-Eโ If set, any trap on ERR gets inherited by shell functions, command substitutions, and commands run in a subshell environment ๐ช. The ERR trap normally isn't inherited in those cases.-Hโ Enables!style history substitution ๐ฐ๏ธ. This is on by default when the shell is interactive.-Pโ If set, the shell doesn't resolve symbolic links when running commands likecdthat change the current working directory ๐บ๏ธ. It uses the physical directory structure instead. By default, bash follows the logical chain of directories when running commands that change the current directory.-Tโ If set, any traps on DEBUG and RETURN get inherited by shell functions, command substitutions, and commands run in a subshell environment ๐. Normally the DEBUG and RETURN traps aren't inherited in those cases.--โ If no arguments follow this option, it unsets the positional parameters ๐งน. Otherwise, it sets the positional parameters to the args, even if some of them begin with a-.-โ Signals the end of options and assigns all remaining args to the positional parameters ๐. The-xand-voptions get turned off. If there are no args, the positional parameters stay unchanged.
The options are off by default unless otherwise noted ๐
. Using + instead of - turns these options off. The options can also be specified as arguments when you invoke the shell ๐. You can find the current set of options in $- ๐. The return status is always zero unless an invalid option is encountered ๐ฏ.
๐ฆ shift [n]
Shifts the positional parameters so that n+1 ... becomes $1 .... Parameters represented by the numbers $# down to $#-n+1 get unset ๐ซง. n must be a non-negative number that's less than or equal to $#. If n is 0, no parameters get changed. If n isn't given, it's assumed to be 1. If n is greater than $#, the positional parameters don't change. The return status is greater than zero if n is greater than $# or less than zero; otherwise it's 0 โจ.
๐
shopt [-pqsu] [-o] [optname ...]
Toggles the values of settings that control optional shell behavior ๐๏ธ. The settings can be either the ones listed below or, if the -o option is used, the ones available with the -o option to the set builtin command.
With no options, or with the -p option, you get a list of all settable options, showing whether each one is set ๐. If any optnames are supplied, the output gets restricted to those. The -p option displays output in a form that can be reused as input ๐.
Here's what the other options do:
-sโ Enables (sets) each optname ๐ข.-uโ Disables (unsets) each optname ๐ด.-qโ Suppresses normal output (quiet mode) ๐คซ. The return status tells you 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, and non-zero otherwise.-oโ Restricts the values of optname to the ones defined for the-ooption to thesetbuiltin ๐ฏ.
If either -s or -u is used with no optname arguments, shopt shows only the options that 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, and non-zero otherwise. When setting or unsetting options, the return status is zero unless an optname isn't a valid shell option ๐.
The list of shopt options is:
array_expand_onceโ okay bestie, when this is set ๐ the shell stops evaluating associative and indexed array subscripts more than once during arithmetic expression evaluation, while running builtins that can do variable assignments, and while running builtins that do array dereferencing ๐ฅassoc_expand_onceโ Deprecated ๐ it's basically an old name forarray_expand_once, still hanging around as a synonym.autocdโ if set, typing a directory's name as a command just cd's you right there ๐ฆ like the shell is reading your mind. Only interactive shells use this one ๐bash_source_fullpathโ if set, filenames that get added to theBASH_SOURCEarray variable turn into full pathnames ๐บ๏ธ (peek at Shell Variables above if you want the deets ๐ง)cdable_varsโ if set, when you givecdsomething that isn't a directory, bash assumes it's a variable name and takes you to whatever directory that variable holds ๐ธcdspellโ if set,cdtries to fix tiny spelling slips in a directory name ๐ซถ we're talking transposed characters, one missing character, or one extra character. If it fixes things, it prints the corrected filename and keeps going. Only interactive shells get this one โจcheckhashโ if set, bash double-checks that a command in the hash table still exists before trying to run it ๐ If the hashed command is gone, bash does a normal path search instead.checkjobsโ if set, before an interactive shell exits, bash lists the status of any stopped and running jobs ๐ If jobs are still running, bash holds off on exiting until you try to exit a second time without any command in between (see JOB CONTROL inbash(1)). The shell always postpones exiting if any jobs are stopped ๐checkwinsizeโ if set, after each external (non-builtin) command bash checks the window size and, if needed, updatesLINESandCOLUMNS, using the file descriptor associated with standard error if it's a terminal ๐ Enabled by default โจcmdhistโ if set, bash tries to save every line of a multi-line command in one single history entry ๐ which makes re-editing multi-line commands so easy. Enabled by default, but it only has an effect if command history is enabled, as described inbash(1)under HISTORY ๐compat31,compat32,compat40,compat41,compat42,compat43,compat44โ these control different aspects of the shell's compatibility mode (see SHELL COMPATIBILITY MODE inbash(1)) ๐complete_fullquoteโ if set, bash quotes all shell metacharacters in filenames and directory names when doing completion ๐ If it's not set, bash drops metacharacters like the dollar sign from the set of characters that get quoted in completed filenames when they show up in shell variable references in the words being completed. So dollar signs in variable names that expand to directories won't get quoted, but any dollar signs appearing in filenames won't get quoted either ๐ญ This only matters when bash is using backslashes to quote completed filenames. This variable is set by default, which is the default bash behavior through versions 4.2 ๐direxpandโ if set, bash swaps directory names for the results of word expansion during filename completion ๐ which changes what's in the readline editing buffer. If it's not set, bash tries to keep exactly what you typed ๐งdirspellโ if set, when the directory name you gave doesn't exist, bash tries spelling correction on directory names during word completion ๐dotglobโ if set, bash includes filenames starting with a dot in the results of pathname expansion ๐ The filenames.and..must always be matched explicitly, even whendotglobis set ๐ซถexecfailโ if set, a non-interactive shell won't exit if it can't execute the file given as an argument to theexecbuiltin ๐ช An interactive shell doesn't exit ifexecfails either.expand_aliasesโ if set, aliases get expanded as described inbash(1)under ALIASES ๐ฆ Enabled by default for interactive shells.extdebugโ if set at shell invocation, or in a shell startup file, it runs the debugger profile before the shell starts, identical to the--debuggeroption ๐ง If it's set after invocation, debugger-friendly behavior switches on:- The
-Foption to thedeclarebuiltin displays the source file name and line number corresponding to each function name supplied as an argument. - If the command run by the
DEBUGtrap returns a non-zero value, the next command is skipped and not executed. - If the command run by the
DEBUGtrap returns a value of2, and the shell is executing in a subroutine (a shell function or a shell script executed by the.orsourcebuiltins), the shell simulates a call toreturn. BASH_ARGCandBASH_ARGVare updated as described in their descriptions inbash(1)).- Function tracing is enabled: command substitution, shell functions, and subshells invoked with
( command )inherit theDEBUGandRETURNtraps. - Error tracing is enabled: command substitution, shell functions, and subshells invoked with
( command )inherit theERRtrap.
- The
extglobโ if set, the extended pattern matching features described inbash(1)under Pathname Expansion get turned on ๐ main character energy ๐extquoteโ if set,$'string'and$"string"quoting gets performed within${parameter}expansions enclosed in double quotes ๐ Enabled by default.failglobโ if set, patterns that fail to match any filenames during pathname expansion result in an expansion error ๐ฅforce_fignoreโ if set, the suffixes listed in theFIGNOREshell variable make words get ignored during word completion, even if the ignored words are the only possible completions ๐ See Shell Variables inbash(1)for a description ofFIGNORE. Enabled by default.globasciirangesโ if set, range expressions used in pattern matching bracket expressions (see Pattern Matching inbash(1)) behave as if in the traditional C locale when doing comparisons ๐ So pattern matching doesn't take the current locale's collating sequence into account. That meansbwon't collate betweenAandB, and upper-case and lower-case ASCII characters collate together ๐คglobskipdotsโ if set, pathname expansion will never match the filenames.and.., even if the pattern begins with a dot ๐ Enabled by default.globstarโ if set, the pattern**used in a pathname expansion context matches all files and zero or more directories and subdirectories ๐ณ If the pattern is followed by a/, only directories and subdirectories match.gnu_errfmtโ if set, shell error messages get written in the standard GNU error message format ๐คhistappendโ if set, when the shell exits, the history list gets appended to the file named by theHISTFILEvariable instead of overwriting it ๐histreeditโ if set, and readline is being used, you get the chance to re-edit a failed history substitution ๐histverifyโ if set, and readline is being used, the results of history substitution aren't immediately passed to the shell parser ๐ Instead, the resulting line gets loaded into the readline editing buffer so you can tweak it some more โ๏ธhostcompleteโ if set, and readline is being used, bash tries hostname completion when a word containing an@is being completed (see Completing under READLINE inbash(1)). Enabled by default ๐huponexitโ if set, bash sendsSIGHUPto all jobs when an interactive login shell exits ๐inherit_errexitโ if set, command substitution inherits the value of theerrexitoption, instead of unsetting it in the subshell environment ๐ง 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, just like in a non-interactive shell (see COMMENTS inbash(1)) ๐ฌ Enabled by default.lastpipeโ if set, and job control isn't active, the shell runs the last command of a pipeline that isn't executed in the background in the current shell environment ๐ฐlithistโ ๐ If this is set andcmdhistis enabled, multi-line commands get saved to history with real embedded newlines instead of semicolons wherever that's possible. ๐localvar_inheritโ ๐ฆ If set, a local variable picks up the value and attributes of a same-named variable from a previous scope before you assign it anything new. The nameref attribute does not get inherited, so don't count on that one. ๐localvar_unsetโ ๐ธ If set, unsetting a local variable from an earlier function scope marks it so later lookups find it unset until that function returns. This works exactly the same as unsetting a local at the current function scope. โจlogin_shellโ ๐ The shell sets this one itself if it was started as a login shell (see INVOCATION in bash(1)). You can't change it. ๐mailwarnโ ๐ฌ If set, and a file bash is checking for mail has been accessed since the last time it was checked, bash displays the message
๐จ Heads up bestie, the original page just cuts off right there after "displays the message." Nothing else is written after it, so that's all I've got for this one. ๐ซถ
no_empty_cmd_completionโ ๐ If set, and readline is in use, bash won't searchPATHfor possible completions when you try to complete on an empty line. ๐nocaseglobโ ๐ค If set, bash matches filenames case-insensitively during pathname expansion (see Pathname Expansion in bash(1)). ๐nocasematchโ ๐ก If set, bash matches patterns case-insensitively incaseand[[conditional commands, in pattern substitution word expansions, and when filtering possible completions as part of programmable completion. It's giving case-blind energy. ๐noexpand_translationโ ๐ If set, bash wraps the translated results of$...quoting in single quotes instead of double quotes. If the string doesn't get translated, this does nothing at all. ๐ซnullglobโ ๐ซฅ If set, pathname expansion patterns that match no files (see Pathname Expansion in bash(1)) vanish into nothing and get removed, instead of expanding to themselves. ๐๏ธpatsub_replacementโ โ๏ธ If set, bash swaps every&in the replacement string of a pattern substitution for the text the pattern matched (as described under Parameter Expansion in bash(1)). This one is enabled by default. ๐progcompโ โญ If set, the programmable completion facilities are turned on (see Programmable Completion in bash(1)). This one is enabled by default. ๐progcomp_aliasโ ๐ง If set, and programmable completion is enabled, a command name with no completions gets treated as a possible alias, and bash tries alias expansion on it. If it turns out to be an alias, bash tries programmable completion using the command word from the expanded alias. Main character energy. ๐promptvarsโ ๐จ If set, prompt strings get parameter expansion, command substitution, arithmetic expansion, and quote removal after they've been expanded the way PROMPTING in bash(1) describes. This one is enabled by default. ๐ธrestricted_shellโ ๐ง The shell sets this one if it was started in restricted mode (see RESTRICTED SHELL in bash(1)). You can't change the value. It doesn't get reset when the startup files run, so those startup files can check whether a shell is restricted. Iconic. ๐ต๏ธshift_verboseโ ๐ข If set, theshiftbuiltin prints an error message when the shift count goes over the number of positional parameters. ๐sourcepathโ ๐บ๏ธ If set, the.(source) builtin uses the value ofPATHto find the directory containing the file you pass in, as long as the-poption isn't supplied. This one is enabled by default. ๐ฆvarredir_closeโ ๐ If set, the shell automatically closes file descriptors assigned through the{varname}redirection syntax (see REDIRECTION in bash(1)) when the command finishes, instead of leaving them open. ๐ซถsyslog_historyโ ๐ชต If set, command history gets logged to syslog. ๐xpg_echoโ ๐ If set, theechobuiltin expands backslash-escape sequences by default. If theposixshell option is also enabled,echodoesn't interpret any options at all. Not me being dramatic, it's literally how it works. ๐
๐ธ suspend [-f]
suspend [-f]
Suspend the execution of this shell until it gets a SIGCONT signal. A login shell, or a shell without job control enabled, can't be suspended. The -f option overrides this and forces the suspension. The return status is 0 unless the shell is a login shell, or job control isn't enabled and -f isn't supplied. ๐ญ
๐ง test expr / [ expr ]
test expr
[ expr ]
Return a status of 0 (true) or 1 (false) depending on whether the conditional expression expr evaluates to true. Every operator and operand has to be its own separate argument. Expressions are built from the primaries described in bash(1) under CONDITIONAL EXPRESSIONS. test doesn't take any options, and it also won't accept and ignore a -- argument as the end-of-options marker. ๐
โโ๏ธ
Expressions can be combined with the operators below, listed in decreasing order of precedence. How they get evaluated depends on the number of arguments (more on that below). test uses operator precedence when there are five or more arguments. ๐งฎ
! exprโ ๐ซ True ifexpris false.( expr )โ ๐ช Returns the value ofexpr. You can use this to override the normal operator precedence.expr1 -a expr2โ ๐ค True if bothexpr1andexpr2are true.expr1 -o expr2โ ๐ True if eitherexpr1orexpr2is true.
test and [ evaluate conditional expressions using a set of rules based on how many arguments they get. ๐ฏ
- 0 arguments โ ๐ซฅ The expression is false.
- 1 argument โ โ The expression is true if and only if the argument is not null.
- 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 that unary test is true. If the first argument isn't a valid unary conditional operator, the expression is false. - 3 arguments โ ๐ข These conditions get applied in the order listed. If the second argument is one of the binary conditional operators listed in bash(1) under CONDITIONAL EXPRESSIONS, the result is the result of the binary test using the first and third arguments as operands. The
-aand-ooperators count as binary operators when there are three arguments. If the first argument is!, the value is the negation of the two-argument test using the second and third arguments. If the first argument is exactly(and the third argument is exactly), the result is the one-argument test of the second argument. Otherwise, the expression is false. - 4 arguments โ 4๏ธโฃ These conditions get applied in the order listed. If the first argument is
!, the result is the negation of the three-argument expression made from the remaining arguments. 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. Otherwise, the expression gets parsed and evaluated according to precedence, using the rules listed above. - 5 or more arguments โ ๐ง The expression gets parsed and evaluated according to precedence, using the rules listed above.
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. ๐
โ ๏ธ The old-school operator-precedence parsing with 4 or more arguments can get ambiguous when it runs into strings that look like primaries. POSIX has deprecated the-aand-oprimaries, and also enclosing expressions within parentheses, so scripts should stop using them. It's way more reliable to limittestinvocations to a single primary, and to swap out-aand-ofor the shell's&&and||list operators instead. ๐
โฑ๏ธ times
times
Print the accumulated user and system times for the shell itself and for processes run from the shell. The return status is 0. โฐ
๐ชค trap [-lpP] [[action] sigspec ...]
trap [-lpP] [[action] sigspec ...]
The action is a command that gets read and executed when the shell receives any of the signals in sigspec. If action is absent (and there's a single sigspec) or -, each specified sigspec gets reset to whatever value it had when the shell started. If action is the null string, the signal specified by each sigspec is ignored by the shell and by the commands it invokes. ๐โจ
Okay so, the trap section isn't done yet bestie, and it's about to get good ๐ฅ. With no arguments, trap shows the actions tied to each trapped signal as a bunch of trap commands you can paste right back into the shell to restore the current signal dispositions ๐
. With -p and no action, it shows the actions for each sigspec, or for every trapped signal if you don't give any, in that same reusable format โจ. -P is similar, but it only shows the actions for each sigspec argument, and it needs at least one sigspec ๐ฆ. Both -p and -P work in subshell environments too, like command substitution. As long as you use them before trap changes a signal's handling, they'll show the state of the parent's traps ๐ซถ.
The -l option prints a list of signal names and their corresponding 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, so int and SIGINT are both fine ๐. If you use -l with no sigspec arguments, it prints a list of valid signal names ๐.
If a sigspec is EXIT (0), the action runs when the shell exits ๐ช. If a sigspec is DEBUG, the 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)) ๐ง. Check out the description of the extdebug shell option (see shopt in bash(1)) for the details on how it changes the DEBUG trap, because it's giving main character energy ๐. If a sigspec is RETURN, the action runs each time a shell function, or a script run with the . or source builtins, finishes executing ๐.
If a sigspec is ERR, the action runs whenever a pipeline (which can be a single simple command), a list, or a compound command returns a non-zero exit status ๐. There are some exceptions though, so pay attention ๐. The ERR trap is not executed if the failed command is part of the command list right after a while or until reserved word, part of the test in an if statement, or part of a command run in a && or || list, except the command after the final && or ||. It also doesn't fire for any command in a pipeline except the last one (this depends on the state of the pipefail shell option), or if the command's return value is being inverted using ! ๐ญ. These are the same conditions that the errexit (-e) option follows, so if you know that one, you already know this one ๐.
When the shell isn't interactive, signals that were ignored when the shell started can't be trapped, reset, or listed ๐
. Interactive shells are allowed to trap signals that were ignored on entry ๐. Trapped signals that aren't being ignored get reset to their original values in a subshell or subshell environment whenever one gets created ๐ธ. The return status is false if any sigspec is invalid, otherwise trap returns true โ
.
โจ true โจ
Does nothing, and returns a 0 status ๐ฆ.
โจ type โจ
type [-aftpP] name [name ...]
Tells you how each name would be interpreted if you used it as a command name ๐.
If you use -t, type prints one of these strings: alias, keyword, function, builtin, or file, depending on whether name is an alias, shell reserved word, function, builtin, or executable file ๐
. If the name isn't found at all, type prints nothing and returns a non-zero exit status ๐.
If you use -p, type either returns the pathname of the executable file that would be found by searching $PATH for name, or prints nothing if it wouldn't return a file ๐บ๏ธ. -P forces a PATH search for each name, even when it wouldn't return a file ๐ฅ. If name is in the table of hashed commands, -p and -P print the hashed value, which isn't always the file that shows up first in PATH ๐.
If you use -a, type prints every place that has a command called name โจ. That includes aliases, reserved words, functions, and builtins ๐. You can still add the path search options (-p and -P) to limit the output to executable files ๐ซถ. type doesn't check the table of hashed commands when you use -a with -p, and it only does a PATH search for name ๐ง.
The -f option turns off shell function lookup, same as the command builtin ๐. type returns true if all of the arguments are found, and false if any of them aren't ๐.
โจ ulimit โจ
ulimit [-HS] -a
ulimit [-HS] [-bcdefiklmnpqrstuvxPRT [limit]]
This one gives you control over the resources available to the shell and to the processes it starts, on systems that allow that kind of control ๐ช.
The -H and -S options decide whether the hard or soft limit gets set for the given resource ๐ฆ. A non-root user can't raise a hard limit once it's set, but a soft limit can go up to the value of the hard limit ๐ญ. If you don't specify -H or -S, ulimit sets both the soft and hard limits ๐.
The value of limit can be a number in the unit for that resource, or one of the special values hard, soft, or unlimited ๐ธ. Those stand for the current hard limit, the current soft limit, and no limit, respectively ๐. If you leave limit out, ulimit prints the current soft limit for the resource, unless you gave it -H โจ. When you specify more than one resource, the limit name and unit (if it applies) get printed before the value ๐. Here's what the other options do:
-aโ Reports all current limits. No limits get set when you use this one ๐ซถ.-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. Lots of systems don't honor this limit, so heads up ๐.-nโ The maximum number of open file descriptors. Most systems don't let you set this value ๐ซ.-pโ The pipe size in 512-byte blocks. This one 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 you pass a limit and don't use -a, that limit becomes the new value for the specified resource ๐ฏ. If you don't supply an option, -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; and -P, -T, -b, -k, -n, and -u, which are unscaled values ๐งฎ. In posix mode, -c and -f are in 512-byte increments instead ๐. The return status is 0 unless you supply an invalid option or argument, or an error happens while setting a new limit ๐ฆ. In POSIX Mode, 512-byte blocks are used for the -c and -f options ๐.
โจ umask โจ
umask [-p] [-S] [mode]
This sets the user file-creation mask to mode ๐. If mode starts with a digit, it's read as an octal number. Otherwise it's read as a symbolic mode mask, similar to what chmod(1) accepts ๐ฆ. If you leave mode out, umask prints the current value of the mask ๐.
The -S option without a mode argument prints the mask in symbolic format. By default the output is an octal number ๐. If you use -p and leave mode out, the output is in a form you can reuse as input ๐ซถ.
The return status is zero if the mode was changed successfully, or if no mode argument was supplied. It's non-zero otherwise ๐ฏ.
โจ unalias โจ
unalias [-a] [name ...]
Removes each name from the list of defined aliases ๐๏ธ. If you use -a, every alias definition gets removed ๐ฅ. The return value is true unless a supplied name isn't a defined alias โ
.
โจ unset โจ
unset [-fv] [-n] [name ...]
For each name, this removes the matching variable or function ๐งน. With -v, each name refers to a shell variable, and that variable gets removed ๐. With -f, each name refers to a shell function, and the function definition gets removed ๐ฅ. If you use -n and name is a variable with the nameref attribute, then name itself gets unset, not the variable it references ๐ช. -n does nothing if you also supply -f ๐
.
Read-only variables and functions can't be unset ๐. When variables or functions get removed, they're also removed from the environment passed to later commands ๐ธ. If you don't supply any options, each name refers to a variable. If there's no variable with that name, any function with that name gets unset instead ๐ง.
Some shell variables can't be unset at all ๐ซ. If any of these get unset, they lose their special properties, even if you reset them later: BASH_ALIASES, BASH_ARGV0, BASH_CMDS, BASH_COMMAND, BASH_SUBSHELL, BASHPID, COMP_WORDBREAKS, DIRSTACK, EPOCHREALTIME, EPOCHSECONDS, FUNCNAME, GROUPS, HISTCMD, LINENO, RANDOM, SECONDS, or SRANDOM ๐ญ.
The exit status is true unless a name is readonly or can't be unset ๐.
โจ wait โจ
wait [-fn] [-p varname] [id ...]
This waits for each specified child process id and returns the termination status of the last id โณ. Each id can be a process ID pid or a job specification jobspec. If you give a jobspec, wait waits for all the processes in that job ๐ซถ.
If you don't supply any options or *id*s, wait waits for all running background jobs and the last-executed process substitution, if its process ID is the same as $!. The return status is zero in that case ๐.
If you pass -n, wait waits for any one of the ids you give it (or, if you give none, any job or process substitution) to finish, then hands back its exit status ๐
. If none of your ids is a child of the shell, or you gave no ids and the shell has no unwaited-for children, the exit status is 127 ๐.
The -p option is the cute one ๐ฆ. It assigns the process or job identifier of the job the returned exit status belongs to into the variable varname, which you name as the option argument. That variable can't be readonly, and it gets unset first, before any assignment happens. It's only useful alongside -n, so don't expect it to do much on its own.
Supplying -f while job control is enabled makes wait wait for each id to actually terminate before returning its status, instead of returning as soon as one changes status ๐ฅ.
If none of the ids is one of the shell's active child processes, the return status is 127. If a signal interrupts wait, any varname stays unset and the return status goes above 128, as described under SIGNALS in bash(1). Otherwise, the return status is the exit status of the last id.
โจ SHELL COMPATIBILITY MODE โจ
Okay so, Bash-4.0 introduced shell compatibility levels, which you set as options to the shopt builtin (compat31, compat32, compat40, compat41, and so on). Here's the tea: there's only one current compatibility level, because each option is mutually exclusive ๐
. The whole point is to let you pick behaviour from older versions that clashes with newer stuff while you migrate your scripts to current features. It's meant to be a temporary solution, bestie โณ.
This section doesn't mention behaviour that's standard for a particular version. For example, setting compat32 means quoting the right-hand side (rhs) of the regexp matching operator quotes special regexp characters in the word, which is default behaviour in bash-3.2 and later versions.
If you enable, say, compat32, it may affect the behaviour of other compatibility levels up to and including the current one. Each level controls behaviour that changed in that version, but that behaviour may have been present in earlier versions too. For instance, the switch to locale-based comparisons with the [[ command came in bash-4.1, and earlier versions used ASCII-based comparisons, so enabling compat32 turns on ASCII-based comparisons as well. That granularity might not be enough for every use case, so use compatibility levels carefully ๐, and read the docs for a particular feature to find out its current behaviour.
Bash-4.3 introduced a new shell variable, BASH_COMPAT ๐ธ. The value you assign to it (a decimal version number like 4.2, or an integer matching a compatNN option, like 42) determines the compatibility level.
Starting with bash-4.4, bash began deprecating the older compatibility levels. Eventually the options will be removed in favour of BASH_COMPAT.
Bash-5.0 was the final version with an individual shopt option for the previous version. In versions newer than bash-5.0, BASH_COMPAT is the only mechanism to control the compatibility level.
The breakdown below describes the behaviour changes each compatibility level setting controls. The compatNN tag is shorthand for setting the compatibility level to NN using one of these mechanisms. For versions prior to bash-5.0, you can set the level with the corresponding compatNN shopt option. For bash-4.3 and later, BASH_COMPAT is preferred, and it's 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 andstrcmp(3); bash-4.1 and later use the current locale's collation sequence andstrcoll(3).
compat41
- In posix mode,
timemay 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 behaviour 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, sobreakorcontinuein 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_ARGVandBASH_ARGCso 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
breakorcontinuewill cause the subshell to exit. Bash-5.0 and later reset the loop state to prevent the exit. - Variable assignments preceding builtins like
exportandreadonlythat 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
$RANDOMis 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 toRANDOMwill 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
-loption is supplied.
compat51
- The
unsetbuiltin 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 arithmeticforstatement 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 ofA[@], whereAis 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 returnvalue, 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
shoptbuiltin 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 enableextglobbefore the command is executed and word expansions are performed. It will fail at word expansion time ifextglobhasn't been enabled by the time the command is executed.
compat52
- The
testbuiltin uses its historical algorithm to parse parenthesized subexpressions when given five or more arguments. - If the
-por-Poption is supplied to thebindbuiltin,bindtreats 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 โจ
That's the whole page, bestie! ๐ This last bit came from GNU Bash 5.2, dated 2023 January 27, and it's filed under BASH_BUILTINS(1) ๐ฆ๐ Go forth and be iconic ๐โจ
๐ฆ where this page comes from
- fedora 43: bash 5.3.0-2.fc43 ยท GPL-3.0-or-later
- fedora 44: bash 5.3.9-3.fc44 ยท GPL-3.0-or-later
- ๐ girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms