sh(1)
๐ธ sh(1) โ standard and job control shell and command interpreter ๐ธ
okay bestie, buckle up, this is the sh(1) page from the User Commands manual, and it's a whole personality. it's long, it's iconic, and we're doing all of it ๐
โจ NAME โจ
sh, bosh, jsh โ the standard and job control shell and command interpreter ๐
๐ SYNOPSIS ๐
/usr/bin/sh [โabCcefhikmnprstuvxP] [argument]...
/usr/bin/bosh [โabCcefhikmnprstuvxP] [argument]...
/usr/bin/pbosh [โabCcefhikmnprstuvxP] [argument]...
/usr/bin/jsh [โabCcefhikmnprstuvxP] [argument]...
๐ DESCRIPTION ๐
okay so the /usr/bin/sh utility is a command programming language that executes commands read from a terminal or a file. that's the whole vibe. that's what it does. ๐
the name bosh lets you call this implementation even when /usr/bin/sh has been linked to another shell. handy, iykyk.
the jsh utility is an interface to the shell that gives you literally all of the functionality of sh and enables job control (peep the Job Control section below) by default โจ. you can also turn job control on by calling the shell via the standard name and then calling set -m or set -o monitor. and since POSIX requires that job control is auto-enabled for interactive shells, jsh can be seen as an artefact from the historic Bourne Shell โ but it's kept for compatibility. we respect the elders ๐ซถ
pbosh is a shell with strict POSIX mode enabled by default and with bosh specific enhancements disabled. use it to check scripts for portability with the minimal POSIX feature set. it's giving "no fun allowed, only standards" and honestly? we stan ๐
arguments to the shell are listed in the Invocation section below.
๐ฆ Definitions ๐ฆ
- a blank is a tab or a space.
- a name is a sequence of ASCII letters, digits, or underscores, beginning with a letter or an underscore.
- a parameter is a name, a digit, or any of the characters
*,@,#,?,โ,$, and!.
โจ Invocation โจ
if the shell is invoked through exec(2) and the first character of argument zero is โ, commands are initially read from /etc/profile and from $HOME/.profile, if such files exist. next, for interactive shells, commands are read from /etc/sh.shrc and from the file with a name that results from doing Parameter Substitution on the environment variable ENV if the file exists (by default this is the file $HOME/.shrc) ๐
after that, commands are read as described below โ which is also the case when the shell is invoked as /usr/bin/sh.
๐ OPTIONS ๐
the options below are interpreted by the shell on invocation only. note: unless the -c or -s option is specified, the first argument is assumed to be the name of a file containing commands, and the remaining arguments are passed as positional parameters to that command file:
-c stringโ if the-coption is present, commands are read from string, where string is the first non-option argument after-c. the remaining arguments become positional parameters starting at$0.
optional options between-cand string have not been supported by older versions ofsh๐
-iโ if the-ioption is present, or if the shell input and output are attached to a terminal, this shell is interactive. in this case,TERMINATEis ignored (so thatkill 0does not kill an interactive shell) andINTERRUPTis caught and ignored (so thatwaitis interruptible). in all cases,QUITis ignored by the shell.-pโ if the-poption is present, the shell does not set the effective user and group IDs to the real user and group IDs.-rโ if the-roption is present, the shell is a restricted shell (seersh(8)).-sโ if the-soption is present or if no arguments remain, commands are read from the standard input. any remaining arguments specify the positional parameters. shell output (except for Special Commands) is written to file descriptor2.-versionโ print the current Bourne Shell version and exit.
using + rather than - causes the related options to be turned off ๐ซถ
the remaining options and arguments are described under the set command below.
๐ฅ USAGE ๐ฅ
๐ Commands ๐
a simple-command is a sequence of non-blank words separated by blanks. the first word specifies the name of the command to be executed. except as specified below, the remaining words are passed as arguments to the invoked command. the command name is passed as argument 0 (see exec(2)). the value of a simple-command is its exit status if it terminates normally, or (octal) 200+status if it terminates abnormally. see signal.h(3HEAD) for a list of status values. no cap, that's the whole thing โจ
a pipeline is a sequence of one or more commands separated by |. the standard output of each command but the last is connected by pipe(2) to the standard input of the next command. if the extended pipe syntax is enabled via set -o fdpipe, the pipe symbol (|) may be preceded by a digit that specifies the file descriptor which should be associated to the command from the left side instead of the default stdout, e.g. 2| for a pipe from stderr ๐ฅ each command is run as a separate process. the shell waits for the last command to terminate. the exit status of a pipeline is the exit status of the last command in the pipeline. each pipeline can be preceded by the reserved word ! โ this causes the exit status of the pipeline to become 0 if the exit status of the last command is non-zero, and 1 if the exit status of the last command is 0. flipping the script, literally ๐
a list is a sequence of one or more pipelines separated by ;, &, &&, or ||, and optionally terminated by ; or &. of these four symbols, ; and & have equal precedence, which is lower than that of && and ||. the symbols && and || also have equal precedence. a semicolon (;) causes sequential execution of the preceding pipeline โ that is, the shell waits for the pipeline to finish before executing any commands following the semicolon. an ampersand (&) causes asynchronous execution of the preceding pipeline โ that is, the shell does not wait for that pipeline to finish. the symbol && (||) causes the list following it to be executed only if the preceding pipeline returns a zero (non-zero) exit status. an arbitrary number of newlines can appear in a list, instead of semicolons, to delimit commands. multi-line slay ๐ฆ
a command is either a simple-command or one of the following. unless otherwise stated, the value returned by a command is that of the last simple-command executed in the command.
for name [ in word ... ] do list doneโ each time aforcommand is executed, name is set to the next word taken from thein wordlist. ifin word ...is omitted, then theforcommand executes thedo listonce for each positional parameter that is set (see the Parameter Substitution section below). execution ends when there are no more words in the list.select name [ in word ... ] do list doneโ theselectcommand prints on standard error (file descriptor2) the set of words, each preceded by a number. ifin word ...is omitted, then the positional parameters are used instead (see Parameter Substitution). thePS3prompt is printed and a line is read from the standard input. if this line consists of the number of one of the listed words, then the value of the variable name is set to the word corresponding to this number. if this line is empty, the selection list is printed again. otherwise the value of the variable name is set toNULL(see Blank Interpretation aboutNULL). the contents of the line read from standard input is saved in the shell variableREPLY. the list is executed for each selection until abreakorEOFis encountered. if theREPLYvariable is set toNULLby the execution of list, then the selection list is printed before displaying thePS3prompt for the next selection.
theselectkeyword was not supported by older versions ofshand is not required by POSIX ๐
case word in [ [(] pattern [ | pattern ] ) list ;; ] ... esacโ acasecommand executes the list associated with the first pattern that matches word. the form of the patterns is the same as that used for file-name generation (see the File Name Generation section), except that a slash, a leading dot, or a dot immediately following a slash need not be matched explicitly.
the ;; operator causes execution of case to terminate. if ;& is used in place of ;; the next subsequent list, if any, is executed โ this causes a fall through to the next command list. if ;;& is used in place of ;;, the shell tests the next pattern list in the statement, if any, and executes any associated list on a successful match. three flavors, all iconic ๐ญ
when not in POSIX mode, sh implements a fallback to a simple string compare, in case that an attempt to match the pattern similar to fnmatch(3) fails.
the optional opening parenthesis was not supported by older versions of sh. it has been added as it is required by POSIX ๐ซถ
if list then list [ elif list then list ] ... [ else list ] fiโ the list followingifis executed and, if it returns a zero exit status, the list following the firstthenis executed. otherwise, the list followingelifis executed and, if its value is zero, the list following the nextthenis executed. failing that, theelselist is executed. if noelselist orthenlist is executed, then theifcommand returns a zero exit status. conditional queen ๐while list do list doneuntil list do list doneโ awhilecommand repeatedly executes thewhilelist and, if the exit status of the last command in the list is zero, executes thedolist; otherwise the loop terminates. if no commands in thedolist are executed, then thewhilecommand returns a zero exit status;untilcan be used in place ofwhileto negate the loop termination test. looping bestie ๐(list)โ execute list in a sub-shell.{ list;}โ list is executed in the current (that is, parent) shell. the{must be followed by a space. โ ๏ธ do not forget the space, fr fr.name () { list;}โ define a function which is referenced by name. the body of the function is the list of commands between{and}. the{must be followed by a space. execution of functions is described below (see the Execution section). the{and}are unnecessary if the body of the function is a command as defined above, under Commands.
okay so next up, time pipeline โ the pipeline gets executed and then the elapsed time plus the user and system time get printed to standard error. You can set the TIMEFORMAT variable to a format string that specifies how that timing info should be displayed. Command based timing from set -o time is temporarily disabled while pipeline based timing is in effect. And if time is followed by white space and a -, it's interpreted as a normal command in order to permit time -p, as required by POSIX. periodt.
POSIX does not require time to be a keyword, iykyk.
The following words are only recognized as the first word of a command and when not quoted:
! if then else elif fi case
esac for while until do done { }
select time
The reserved words !, select and time were not supported in older versions of sh. okay vintage icon behavior ๐
๐ธ Comments Lines ๐ธ
A word beginning with # causes that word and all the following characters up to a newline to be ignored. classic, love that for us.
๐ # commands ๐
If the hash character # is the first character in a command line and hash commands have been enabled via set -o hashcmds, the whole line is processed by the hash command interpreter. This allows one to have an alternate entry to the alias definitions that avoids complex quoting by working on the raw alias definitions.
Hash commands are frequently used to edit alias definitions using the command line history editor.
no cap on the limits though: no I/O redirection is possible for hash commands. No exit code is created for hash commands, $? is left intact from the last regular command. Quoting is not possible for hash commands. For all hash commands, there is a built in help text that is printed when #c -help is called, where c is one of the command letters.
When hash commands are enabled, the character that immediately follows the # is the command character. The command character may be followed by one or more command modifier characters. The following commands are supported:
#a[g|l] name valueโ add a new all expand alias. Such an alias is expanded regardless where it occurs on the command line. Without modifier, the alias is entered into the current default table.- The first word surrounded by spaces is taken as the alias name, after skipping spaces, all text up to the end of the line is taken as the alias value.
- When using the
'g'modifier, the command works on global aliases, regardless of the current default. - When using the
'l'modifier, the command works on local aliases, regardless of the current default. - At startup, the default is to use the global aliases.
#b[g|l] name valueโ add a new begin alias. Such an alias is only expanded for the first word in a command. Without modifier, the alias is entered into the current default table.#d[g|l] nameโ removes the alias name from the list of known aliases. Without modifier, the alias is removed from the current default table.#h#?โ print an overview help for all#commands.#l[g|l][h] [name]โ lists aliases from the table. Without modifier, the aliases from the current default table are printed. Without name, all aliases are listed. With name, only matching aliases are listed. Wildcards may be used.- When using the
'h'modifier, the alias is also entered into the command history. This permits editing of existing aliases with the history editor and to re-enter the modified entries into the list of aliases.
- When using the
#p[g|l][a|b] name valueโ with the#pcommand, an alias may be pushed on top of an existing alias without writing to the related file. When a pushed value is removed, the old definition reappears.- When using the
'a'modifier, an all expand alias is pushed. - When using the
'b'modifier, a begin alias is pushed.
- When using the
#s[g|l]โ set or list the default table for other#command alias operations. If no modifier letter is used, the current default is printed otherwise the new default is set.#โ in interactive mode, when entered as first character on the command line, this prints the shell version.
โ ๏ธ bestie read this one fr fr: after the commandset -o hashcmdshas been issued in a shell script, a#as first character of a command line inside that shell script, if followed by a non-space character is no longer interpreted as a comment. This may be a problem in the file$HOME/.shrcas this file is typically used to enable hashcmds viaset -o hashcmdsfor an interactive shell. It is thus recommended to haveset -o hashcmdsclose to the bottom of the file$HOME/.shrc. like literally put it at the bottom, trust ๐
๐ฆ Alias Substitution ๐ฆ
After a token has been recognized, but before applying the grammatical rules, a resulting word that is identified as the command name of a simple command is examined whether it is an unquoted valid alias name. A valid alias name is replaced by the value of the alias. The shell prevents infinite alias loops by not expanding the same alias more than once for the same word. no infinite recursion era ๐ โโ๏ธ
Alias expansion is performed when the commands are read, not when they are executed. timing matters bestie โจ
Aliases can be used to redefine built-in commands but cannot be used to redefine the reserved words listed in the Commands section. Aliases can be created and listed with the alias command and removed with the unalias command.
POSIX compliant temporary alias definitions are not inherited by separate invocations of the shell or when interpreting scripts.
The Bourne Shell implements enhanced alias features beyond the POSIX alias definition. Enhanced alias features are disabled by default. They need to be turned on (see set command below) to make them operational. The following additional alias features are available:
- persistent aliases โ if turned on by
set -o globalaliases, persistent global aliases are automatically loaded by all interactive shells. - local aliases โ if turned on by
set -o localaliases, persistent local aliases are automatically loaded by all interactive shells as a result of thecdcommand. Local aliases are specific to the current working directory. The local aliases definitions from the previous working directory are automatically disabled when the working directory is changed to a different directory. Local aliases have higher precedence than global aliases. local girlies stay winning ๐
๐ Tilde Expansion ๐
A tilde-prefix consists of an unquoted tilde character at the beginning of a word, followed by all of the characters preceding the first unquoted slash in the word, or all the characters in the word if there is no slash. In an assignment, multiple tilde-prefixes can be used: at the beginning of the word (that is, following the equal sign of the assignment), following any unquoted colon or both. A tilde-prefix in an assignment is terminated by the first unquoted colon or slash. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name from the user database.
A portable login name cannot contain characters outside the set given in the description of the LOGNAME environment variable. If the login name is null (that is, the tilde-prefix contains only the tilde), the tilde-prefix is replaced by the value of the variable HOME. If HOME is unset, the results are unspecified. Otherwise, the tilde-prefix is replaced by a pathname of the home directory associated with the login name obtained using the getpwnam function. If the system does not recognize the login name, the results are undefined. ๐
Tilde expansion generally occurs only at the beginning of words, but an exception based on historical practice has been included:
PATH=/usr/xpg4/bin:~joerg/bin
is eligible for tilde expansion because tilde follows a colon and none of the relevant characters is quoted. Consideration was given to prohibiting this behavior because any of the following are reasonable substitutes:
PATH=$(printf %s ~karels/bin : ~bostic/bin)
for Dir in ~maart/bin ~srb/bin .
do
PATH=${PATH:+$PATH:}$Dir
done
With the first command, explicit colons are used for each directory. In all cases, the shell performs tilde expansion on each directory because all are separate words to the shell.
Expressions in operands such as:
make -k mumble LIBDIR=~chet/lib
do not qualify as shell variable assignments and tilde expansion is not performed (unless the command does so itself, which make does not). rude of it honestly but okay ๐
Because of the requirement that the word not be quoted, the following are not equivalent; only the last causes tilde expansion:
\~hlj/ ~h\lj/ ~"hlj"/ ~hlj\/ ~hlj/
The results of giving tilde with an unknown login name are undefined by POSIX because the Bourne Shell ~+ and ~- constructs make use of this condition, but in general it is an error to give an incorrect login name with tilde. The results of having HOME unset are unspecified because some historical shells treat this as an error. so likeโฆ be careful bestie ๐ญ
If a tilde that matches the criteria is found, the word up to a / (or up to a : in case of a variable assignment) is checked to see if it matches a user name in the password database. If a match is found, the ~ and the matched login name are replaced by the login directory of the matched user. If no match is found, the original text is left unchanged. A ~ by itself, or in front of a /, is replaced by $HOME. A ~ followed by a + or - is replaced by the value of $PWD and $OLDPWD respectively. the way it just knows where home is ๐ฅน๐
๐ง Command Substitution ๐ง
The shell reads commands enclosed in parenthesis preceded by a dollar sign (that is, $(command)) or from the string between two grave accents (`...`) and the standard output from these commands can be used as all or part of a word. Trailing newlines from the standard output are removed.
No interpretation is done on the string before the string is read, except when using the second (obsolete) form using the backquoted syntax, where backslashes (\) are used to escape other characters.
When using the backquoted syntax, backslashes can be used to escape a grave accent (`) or another backslash (\) and are removed before the command string is read. Escaping grave accents allows nested command substitution in this form. If the command substitution lies within a pair of double quotes (" ... ... ... "), a backslash used to escape a double quote (\") is removed. Otherwise, it is left intact. lowkey the backquote form is giving legacy but it still ate ๐
โจ
Okay so if a backslash is used to escape a newline character (\newline), both the backslash and the newline are removed โ poof ๐จ (peep the later section on Quoting). In addition, backslashes used to escape dollar signs (\$) are removed. Since no parameter substitution is done on the command string before it's read, inserting a backslash to escape a dollar sign has no effect. Backslashes that come before anything other than \, `, ", newline, and $ are left intact when the command string is read. Slay.
In the $() form, nested command substitutions do not need special quoting. Periodt.
Command substitution allows the output of a command to be substituted in place of the command name itself. Command substitution occurs when the command is enclosed as follows:
$(command)
or the backquoted version:
`command`
The shell expands the command substitution by executing command in a subshell environment and replacing the command substitution (the text of command plus the enclosing $() or backquotes) with the standard output of the command, removing sequences of one or more newline characters at the end of the substitution. Embedded newline characters before the end of the output are not removed; however, they can be treated as field delimiters and eliminated during field splitting, depending on the value of IFS and quoting that is in effect. Iconic.
With the $(command) form, all characters following the open parenthesis to the matching closing parenthesis constitute the command. Any valid shell script can be used for command.
Lowkey important: the results of command substitution are not field splitting and pathname expansion processed for further tilde expansion, parameter expansion, command substitution or arithmetic expansion. If a command substitution occurs inside double-quotes, it is not performed on the results of the substitution.
The $() form of command substitution solves a problem of inconsistent behavior when using backquotes. For example:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Command Output โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ echo '\$x' \$x โ
โ echo `echo '\$x'` $x โ
โ echo $(echo '\$x') \$x โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Additionally, the backquoted syntax has historical restrictions on the contents of the embedded command. While the new $() form can process any kind of valid embedded script, the backquoted form cannot handle some valid scripts that include backquotes. For example, these otherwise valid embedded scripts do not work in the left column, but do work on the right:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ echo ` echo $( โ
โ cat <<eof cat <<eof โ
โ a here-doc with ` a here-doc with ) โ
โ eof eof โ
โ ` ) โ
โ echo ` echo $( โ
โ echo abc # a comment with ` echo abc # a comment with ) โ
โ ` ) โ
โ echo ` echo $( โ
โ echo '`' echo ')' โ
โ ` ) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Because of these inconsistent behaviors, the backquoted variety of command substitution is not recommended for new applications that nest command substitutions or attempt to embed complex scripts. No cap.
If the command substitution consists of a single subshell, such as:
$( (command) )
a portable application must separate the $( and ( into two tokens (that is, separate them with white space). This is required to avoid any ambiguities with arithmetic expansion. Iykyk.
๐งฎ Arithmetic Expansion ๐งฎ
An arithmetic expression enclosed in double parentheses preceded by a dollar sign is replaced by the value of the arithmetic expression within the double parentheses. Arithmetic expansion provides a mechanism for evaluating an arithmetic expression and substituting its value. The format for arithmetic expansion is as follows:
$((arithmetic-expression))
The expression is treated as if it were in double-quotes, except that a double-quote inside the expression is not treated specially. The shell expands all tokens in the expression for parameter expansion, command substitution and quote removal.
Next, the shell treats this as an arithmetic expression and substitutes the value of the expression. The arithmetic expression is processed according to the rules of the ISO C with the following exceptions:
- Only signed long long integer arithmetic is supported.
- The
sizeof()operator is not supported. - Selection, iteration, and jump statements are not supported.
If the expression is invalid, the expansion fails and the shell writes a message to standard error indicating the failure. F in chat ๐ญ.
POSIX does not require to support the prefix and postfix ++ and โโ operators, so avoid them in portable shell scripts.
POSIX does not require to support more than signed long arithmetic, so avoid arithmetic that requires more in portable scripts.
In older versions of sh, arithmetic expansion was not supported. Ancient lore fr.
A simple example using arithmetic expansion:
# repeat a command 100 times
x=100
while [ $x โgt 0 ]
do
command
x=$((xโ1))
done
๐ Parameter Substitution ๐
The character $ is used to introduce substitutable parameters. There are two types of parameters, positional and keyword. If parameter is a digit, it is a positional parameter. Positional parameters can be assigned values by set. Keyword parameters (also known as variables) can be assigned values by writing:
name=value [ name=value ] ...
The evaluation of the assignments is done from the left to the right in this shell.
Pattern-matching is not performed on value. There cannot be a function and a variable with the same name. (Not me checking both like ๐)
${parameter}โ The value, if any, of the parameter is substituted. The braces are required only when parameter is followed by a letter, digit, or underscore that is not to be interpreted as part of its name, or when the parameter name contains a dot (.). If parameter is*or@, all the positional parameters, starting with$1, are substituted (separated by spaces). Parameter$0is set from argument zero when the shell is invoked. Slay.${parameter:โword}โ Use Default Values. If parameter is unset or null, the expansion of word is substituted; otherwise, the value of parameter is substituted.${parameterโword}โ Use Default Values. If parameter is unset, the expansion of word is substituted; otherwise, the value of parameter is substituted.${parameter:=word}โ Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. In all cases, the final value of parameter is substituted. Only variables, not positional parameters or special parameters, can be assigned in this way.${parameter=word}โ Assign Default Values. If parameter is unset, the expansion of word is assigned to parameter. In all cases, the final value of parameter is substituted. Only variables, not positional parameters or special parameters, can be assigned in this way.${parameter:?word}โ Indicate Error if Null or Unset. If parameter is set and is non-null, substitute its value; otherwise, print word and exit from the shell. If word is omitted, the messageparameter null or not setis printed.${parameter?word}โ Indicate Error if Null or Unset. If parameter is set, substitute its value; otherwise, print word and exit from the shell. If word is omitted, the messageparameter null or not setis printed.${parameter:+word}โ Use Alternative Value. If parameter is set and is non-null, substitute word; otherwise substitute nothing.${parameter+word}โ Use Alternative Value. If parameter is set, substitute word; otherwise substitute nothing.
Okay so here's the tea on that colon ๐
โ if the : is left out of the expressions above, the shell is only checking whether parameter is set or not. That's the entire plot twist. Receipts:
โ โ โ
โparameter nonnull โparameter null โparameter unset
โโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
${parameter:-word} โsubst. parameter โsubst. word โsubst. word
โโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
${parameterโword} โsubst. parameter โsubst. null โsubst. word
โโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
${parameter:=word} โsubst. parameter โassign word โassign word
โโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
${parameter=word} โsubst. parameter โsubst. null โassign word
โโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
${parameter:?word} โsubst. parameter โerror, exit โerror, exit
โโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
${parameter?word} โsubst. parameter โsubst. null โerror, exit
โโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
${parameter:+word} โsubst. word โsubst. null โsubst. null
โโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
${parameter+word} โsubst. word โsubst. word โsubst. null
โโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโ
Anywhere the table says "assign", parameter gets assigned that value, and that assignment also replaces the expression. Slay, it's doing two jobs ๐
And bestie, listen โ word is not evaluated unless it's actually gonna be used as the substituted string. So in this next example, pwd runs only if d is unset or null. Like, it literally does not get executed otherwise:
echo ${d:โ`pwd`}
${#parameter} โ String Length. It's the length in characters of the value of parameter. If parameter is * or @, the results are unspecified. (iykyk, just don't ๐)
The next four flavors of parameter expansion are the substring processing girlies. In each case it's pattern matching notation, not regular expression notation, that gets used to evaluate the patterns. If parameter is * or @, the results are unspecified. And heads up ๐ซถ โ wrapping the whole parameter expansion string in double-quotes does not quote these four varieties of pattern characters, whereas quoting characters inside the braces does exactly that.
${parameter%word}โ Remove Smallest Suffix Pattern. word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the suffix matched by the pattern deleted. If word begins with a%, the character needs to be quoted.${parameter%%word}โ Remove Largest Suffix Pattern. word is expanded to produce a pattern. The parameter expansion then results in parameter, with the largest portion of the suffix matched by the pattern deleted.${parameter#word}โ Remove Smallest Prefix Pattern. word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted. If word begins with a#, the character needs to be quoted.${parameter##word}โ Remove Largest Prefix Pattern. word is expanded to produce a pattern. The parameter expansion then results in parameter, with the largest portion of the prefix matched by the pattern deleted.
And now, the parameters the shell sets all by itself โ no cap, they just appear, main character energy only โจ
#โ the number of positional parameters, in decimal.nโ the n-th positional parameter. The parameter name n is in the range from1to$#.0โ parameter$0is set from argument zero when the shell is invoked. If running a script,$0is the name of the script.*โ all positional parameters starting from$1."$*"expands to one argument that contains all positional parameters separated by the first character in theIFSvariable, or by a space, in caseIFSis unset. IfIFSis set to a null string, its first character does not exist, so the parameter values are concatenated.
In older versions of sh, IFS was not evaluated for "$*" and the separator was always a space character.
@โ all positional parameters starting from$1."$@"expands to$#arguments.โโ flags supplied to the shell on invocation or by thesetcommand.?โ the decimal value returned by the last synchronously executed command, or a decimal number derived from the signal number that killed the process.- Only the low 8 bits of the exit code from the command are visible unless exit code masking is switched off by
set -o fullexitcode. Being able to see all 32 bits from the exit code requires a modern UNIX compliant operating system with working support forwaitid(2). - If the executable file could not be found, the returned value is
127. If the file exists but could not be executed, the returned value is126. - If
boshhas been compiled withDO_EXIT_MODFIX(which is not the default and not recommended by POSIX) and if a command's exit code modulo 256 is zero andset -o fullexitcodeis not in effect, the returned value is128, except when the operating system does not supportwaitid(2), as the exit code then is masked by the kernel. - If the command was killed by a signal, the returned value is
128+ the signal number. As a result, apparent exit code values in the range129..200may also have been caused by a signal. ๐ - If the shell itself or a sub shell catches a signal while preparing a job, the exit code is
2000, or (when exit codes are masked to only the low 8 bits)208.
- Only the low 8 bits of the exit code from the command are visible unless exit code masking is switched off by
/โ a decimal number or text indicating the exit status returned by the last synchronously executed command.- If
$/returns a decimal number, this is (on a POSIX system) the 32 bit exit code from the last command that did normally exit. Older non-POSIX systems like Linux or UNIX systems from before SVr4 return only the low 8 bits from the exit code. In any case, the number was a result from a normal program exit. - If
$/returns text, this is either a signal name with the leadingSIGstripped off, likeINT(seekill -l) for the signal that terminated the program, or one of the stringsNOEXECorNOTFOUND, in case the program could not be run at all. The stringsNOEXECandNOTFOUNDare returned reliably fromvfork(2)children or when the related state is already known by the cache. This is true for all simple commands. - Note that unless
set -o fullexitcodeis in effect,$/may have a non-zero value where value mod 256 == 0 and the shell in such a case evaluates conditional execution as if the exit code was zero. This is the default behavior required by POSIX for compatibility with historic shells.
- If
$โ the decimal process number of this shell. In a subshell, this still expands to the same value as that of the current invoked shell.!โ the process number of the last background command invoked..sh.codeโ the numerical reasonwaitid(2)returned for the child status change. It matches theCLD_*definitions fromsignal.h. Note that the numbers are usually in the range1..6but this is not guaranteed. Use${.sh.codename}for portability. ๐ซถ.sh.codenameโ the reasonwaitid(2)returned for the child status change, as text generated by stripping offCLD_from the related definitions fromsignal.h. Possible values are:EXITEDโ the program had a normal termination and theexit(2)code is in${.sh.status}.KILLEDโ the program was killed by a signal, the signal number is in${.sh.status}, the signal name is in${.sh.termsig}.DUMPEDโ the program was killed by a signal, similar toKILLEDabove, but the program in addition created a core dump.TRAPPEDโ a traced child has trapped.STOPPEDโ the program was stopped by a signal, the signal number is in${.sh.status}, the signal name is in${.sh.termsig}.CONTINUEDโ a stopped child was continued.NOEXECโ an existing file could not be executed. This can happen when e.g. either the type of the file is not plain file or when the file does not have execute permission, or when the argument list is too long.
NOEXECโ this one's not awaitid(2)result at all, it comes fromexecve(2). ๐NOTFOUNDโ a file was not found, so obviously it could not be executed. Also not awaitid(2)result โ straight fromexecve(2).
The child codes NOEXEC and NOTFOUND in ${.sh.codename} need shared memory (like, from vfork(2)) to allow a reliable reporting, okurrr.
the ${.sh.โฆ} little icons ๐ธ
.sh.pathโ the absolute path name for the current shell binary, if available..sh.pidโ the process number of the process that caused the currentwaitid(2)status..sh.shellโ the name of the shell. This shell returns:
sh (Schily Bourne Shell)
.sh.signameโ the name of the causing signal. If the status is related to a set ofwaitid(2)return values, this isCHLDorCLD, depending on the os. When atrap(1)command is executed,${.sh.signame}holds the signal that caused the trap..sh.signoโ the signal number related to${.sh.signame}..sh.statusโ the decimal value returned by the last synchronously executed command. The value is unaltered and contains the fullintfrom theexit(2)call in the child in case the shell is run on a modern os..sh.termsigโ the signal name related to the numerical${.sh.status}value. The translation to signal names takes place regardless of whether the child was terminated by a signal or terminated normally..sh.versionโ a string that identifies the version of this shell.
โ ๏ธ bestie be careful: trying to use the ${.sh.xxx} parameters on older shells will cause the older shells to exit with a bad substitution message โ unless the shell is an interactive shell. ๐ญ so like, don't do that.
The following parameters are used by the shell. The parameters in this section are also referred to as environment variables. (same thing, different outfit ๐ )
HOMEโ the default argument (home directory) for thecdcommand, set to the user's login directory bylogin(1)from the password file (seepasswd(5)).PATHโ the search path for commands (see Execution section below). IfPATHis not set, it defaults to/usr/bin:.BEEPโ if set tooff, the history editor will not beep in case of an error. Use this to allow e.g. silent working in meetings. ๐คซBEEPis only supported ifshwas compiled with support for history editing. The variableBEEPwas not supported in older versions ofsh.CDPATHโ the search path for thecdcommand.ENVโ this variable is used when and only when an interactive shell is invoked. It is subject to Parameter Substitution by the shell, and the resulting value is used as the pathname of a script that is executed when the shell is invoked. This file is typically used to define function definitions and transient alias definitions, or to turn on persistent alias features or jobcontrol. The default value is$HOME/.shrc. If the result of the Parameter Substitution starts with/./or./the file/etc/sh.shrcis not executed. ๐ซ The variableENVwas not supported in older versions ofsh. The recommended content of the file${ENV}is:
set -o globalaliases
set -o localaliases
set -o fdpipe
set -o hostprompt
set -o hashcmds
set -o time
Make sure set -o time is the last entry to avoid timing the commands from the .shrc file. โฐ
FCEDITโ the name default editor name for thefccommand.FCEDITis only supported ifshwas compiled with support for history editing. The variableFCEDITwas not supported in older versions ofsh, it is an artefact fromkshand required by a POSIX feature named user portability.HISTFILEโ the name of the file to use in order to read or save the command history. IfHISTFILEis not set before the shell reads the initial history at startup, the name$HOME/.historyis used. IfHISTFILEis set, then the shell will save the history while exiting even in case thatSAVEHISTORYwas not set.HISTFILEis only supported ifshwas compiled with support for history editing. The variableHISTFILEwas not supported in older versions ofsh.HISTORYโ the maximum number of lines to keep in the command history editor. The default is to keep128lines of command history. This is the historic name that is in use since 1984, it is used as a fallback, when the POSIX variableHISTSIZE(introduced 1992) was not set.HISTORYis only supported ifshwas compiled with support for history editing. The variableHISTORYwas not supported in older versions ofsh.HISTSIZEโ the maximum number of lines to keep in the command history editor. The default is to keep128lines of command history. This is the POSIX variable name that has precedence overHISTORY. ๐HISTSIZEis only supported ifshwas compiled with support for history editing. The variableHISTSIZEwas not supported in older versions ofsh.IGNOREEOFโ if set toon, the shell will not exit if a^Dis typed and the cursor is on an empty command line; the commandexitmust be used instead. The default is not to ignore EOF. See also the commandset -o ignoreeofbelow. This is the historic interface that is in use since 1984. The POSIX interface is to callset -o ignoreeof.IGNOREEOFis only supported ifshwas compiled with support for history editing. The variableIGNOREEOFwas not supported in older versions ofsh.LINENOโ the line number of the current line within the script. This variable currently does not have all POSIX features. The variableLINENOwas not supported in older versions ofsh.MAILโ if this parameter is set to the name of a mail file and theMAILPATHparameter is not set, the shell informs the user of the arrival of mail in the specified file. ๐ฌMAILCHECKโ this parameter specifies how often (in seconds) the shell checks for the arrival of mail in the files specified by theMAILPATHorMAILparameters. The default value is600seconds (10 minutes). If set to0, the shell checks before each prompt.MAILPATHโ a colon-separated list of file names. If this parameter is set, the shell informs the user of the arrival of mail in any of the specified files. Each file name can be followed by%and a message that is printed when the modification time changes. The default message is, you have mail.OLDPWDโ the previous working directory, set by thecd, thepushdand thepopdcommand.OLDPWDis not set before the firstcd,pushdorpopdcommand. The variableOLDPWDwas not supported in older versions ofsh.OPTARGโ this variable is used bygetoptsto store the argument if an option is using arguments.OPTINDโ this variable is used bygetoptsas the index of the next argument to be processed.PPIDโ the process number of the parent of the shell. The variable is setup once at program start and then set readonly. ๐ The variablePPIDwas not supported in older versions ofsh.PS1โ primary prompt string, by default"$ "for normal users and"privileged users. Each time an interactive shell is ready to read a command, the value of this variable is subject to parameter expansion and written to standard error. See the description forset -o promptcmdsubstbelow for more information. The variablePS1was not subject to parameter expansion in older versions ofsh.PS2โ secondary prompt string, by default"> ". Each time, the user enters a<newline>prior to completing a command line in an interactive shell, the value of this variable is subject to parameter expansion and written to standard error. See the description forset -o promptcmdsubstbelow for more information. The variablePS2was not subject to parameter expansion in older versions ofsh.PS3โ selection prompt string, by default"#? ". The variablePS3was not supported in older versions ofsh.PS4โ execution trace prompt string, by default"+ ". If unset,"+ "is used. The value of this variable is subject to parameter expansion and written to standard error. See the description forset -o promptcmdsubstbelow for more information. The variablePS4was not supported in older versions ofsh.PWDโ the present working directory, set by thecd, thepushdand thepopdcommand. POSIX requiresPWDto be set and verified at program startup. This may prevent a login for users with a networked home directory in case of a NFS based hang. ๐ The variablePWDwas not supported in older versions ofsh.REPLYโ this variable is set by theselectstatement and by thereadspecial builtin command when no arguments are supplied. The variableREPLYwas not supported in older versions ofsh.IFSโ internal field separators, normally space, tab, and newline (see Blank Interpretation section).SAVEHISTORYโ if set toon, the current history is saved in the file$HOME/.historywhen this shell exits. The default is not to save the history. This is the historic interface that is in use since 1984. The POSIX interface is to setHISTFILEto the absolute path name of the persistent history file. ๐ซถ
...and heads up bestie, SAVEHISTORY is only supported if sh was compiled with support for history editing ๐
and lowkey the variable SAVEHISTORY was not supported in older versions of sh. Not her era, periodt.
SHACCTโ set this bad boy to the name of a file that's writable by the user, and the shell writes an accounting record into that file for each shell procedure executed ๐. Receipts, literally.SHELLโ when the shell is invoked, it scans the environment (peep the Environment section below for the full tea โ) for this name. If the last pathname component equalsrshorrbosh, the shell gets switched into a restricted shell ๐. Main character gets locked down, iykyk.SYSV3โ when theSYSV3Environment is set, the builtinechocommand switches into SYSV3 mode and supports escape sequences plus the BSD-noption to suppress the newline character at the end of the output โจ.TERMโ used to determine the name of the terminal type. If this variable is unset or null, an unspecified default terminal type is used.TERMis only supported ifshwas compiled with support for history editing ๐ธ. Also? The variableTERMwas not supported in older versions ofsh. She was built different back then.TERMCAPโ this variable holds either a precompiled termcap entry or the pathname to be used to find a termcap database file. If it holds a precompiled entry that does not match theTERMenvironment, the termcap database is parsed as if theTERMCAPenvironment is not set.TERMCAPis automatically exported after filling it with a precompiled entry, to speed up termcap based applications ๐ฅ.TERMCAPis only supported ifshwas compiled with support for history editing.
See the NOTES section for hints on what to do when your platform does not provide an /etc/termcap file ๐.
The variable TERMCAP was not supported in older versions of sh.
TERMPATHโ ifTERMCAPis empty or not set, then theTERMPATHenvironment is scanned for pathnames of files that contain a termcap database. It holds a list of filenames separated by colons or spaces (i.e.,":"or" ") ๐. If theTERMPATHsymbol is not set, the files$HOME/.termcapand/etc/termcapare scanned in that order.TERMPATHis only supported ifshwas compiled with support for history editing.
The variable TERMPATH was not supported in older versions of sh.
TIMEFORMATโ controls the output format for command timing โฑ๏ธ. The%character introduces a format sequence that is expanded to a time value or other information.
The meaning of format sequences are as follows:
%%โ Prints a literal%.%pTโ Set the threshold to p seconds, p is a single digit. If the number of seconds computed from adding the user and system cpu time is less than the threshold, the rest of the format string is not processed, except when the timing is a result of using thetimereserved word; if this format appears at the beginning ofTIMEFORMAT, the whole output is suppressed ๐.%Pโ Prints the cpu percentage computed as100*(U + S) / R. On multi-cpu systems, this value may be larger than 100 ๐.%[p][f]Eโ Prints the elapsed (real) wallclock time in seconds.%[p][f]Sโ Prints the number of cpu seconds spend in system mode.%[p][f]Uโ Prints the number of cpu seconds spend in user mode.%Wโ Number of times the process was swapped.%Xโ The average amount in shared text space used in Kbytes. This field is currently not supported.%Dโ The average amount in unshared data space used in Kbytes. This field is currently not supported.%Kโ The average amount of unshared stack space used in Kbytes. This field is currently not supported.%Mโ The maximum memory the process had in use at any time in Kbytes. This field is currently not supported.%Fโ The number of major page faults (page faults that caused physical I/O).%Rโ The number of minor page faults (page faults that did not caused physical I/O).%Iโ The number of input operations%Oโ The number of output operations.%rโ The number of socket messages received.%sโ The number of socket messages sent.%kโ The number of signals received.%wโ Number of voluntary context switches (waits).%cโ Number of involuntary context switches.%Jโ The name of this job. This string is only available when in job control mode ๐.
On some minimal POSIX systems and on BeOS and Haiku only the times are supported ๐ซถ.
The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point to be printed. A value larger than 6 is treated as 6. If p is not specified, the value 3 is used ๐ข.
The optional f is a letter specifying the format to be used. If it is missing, a plain floating point number based on seconds is used. The following characters are supported to specify a different format:
lโ The l-format is the POSIX output format fortimes(1). It always prints minutes and seconds in the following form:ddmdd.ppps.Lโ The L-format is similar to the l-format but it prints hours and minutes where the l-format prints just minutes regardless of whether there are more than 59 minutes. Minutes and hours are only printed if the value is more than 59 seconds or 59 minutes. The format is:ddhddmdd.ppps.:โ The :-format is similar to the L-format but it prints nosafter the seconds and it replacesmandhby:. The format is:dd:dd:dd.ppp.
The value of the decimal point in the floating point formats above is subject to locale specific adoptions based on LC_NUMERIC or LC_ALL ๐.
If TIMEFORMAT is unset, the value:
'%:E real %U user %S sys %P%% cpu'
is used for automatic timing with set -o time and:
'\nreal %6:E\nuser %6U\nsys %6S'
is used for pipelines prefixed with the time reserved word. If TIMEFORMAT is empty, no timing information is printed ๐ถ. A recommended format that is similar to what csh(1) prints by default, but with the available precision from modern operating systems is:
'%6:Er %6Uu %6Ss %P%% %I+%Oio %Fpf+%Ww'
A trailing newline is added when the format string is displayed ๐.
The variable TIMEFORMAT was not supported in older versions of sh.
See environ(7) for descriptions of the following environment variables that affect the execution of sh: LANG, LC_ALL, LC_CTYPE, LC_MESSAGES and LC_NUMERIC.
The shell gives default values to ENV, PATH, PS1, PS2, PS3, PS4, MAILCHECK, HISTORY, OPTIND, and IFS. Default values for HOME and MAIL are set by login(1). For security reasons, the value for IFS is never imported from the environment ๐ โ like, never ever, don't even try.
When the shell is initially in POSIX mode, it marks all variables imported from the environment with the export property. See Environment section below ๐.
๐ Blank Interpretation
After parameter and command substitution, the results of substitution are scanned for internal field separator characters (those found in IFS) and split into distinct arguments where such characters are found ๐. Explicit null arguments ("" or '') are retained. Implicit null arguments (those resulting from parameters that have no values) are removed. Slay, honestly โ she knows exactly what counts as a real argument and what's just vibes.
๐ Input/Output Redirection
A command's input and output can be redirected using a special notation interpreted by the shell ๐ธ. The following can appear anywhere in a simple-command or can precede or follow a command and are not passed on as arguments to the invoked command. Note: Parameter and command substitution occurs before word or digit is used โ ๏ธ.
<wordโ Use file word as standard input (file descriptor 0).>wordโ Use file word as standard output (file descriptor 1). If the file does not exist, it is created. If the file exists, and thenoclobberoption is on, this causes an error ๐ฑ. Otherwise, it is truncated to zero length ๐.>|wordโ Same as>, except that it overrides thenoclobberoption. This feature was not supported in older versions ofshโจ.>>wordโ Use file word as standard output. If the file exists, output is appended to it by first seeking to the EOF. Otherwise, the file is created ๐.<>wordโ Open file word for reading and writing as standard input.<<[โ]wordโ After parameter and command substitution is done on word, the shell input is read up to the first line that literally matches the resulting word, or to an EOF. If, however, the hyphen (โ) is appended to<<:- leading tabs are stripped from word before the shell input is read (but after parameter and command substitution is done on word);
- leading tabs are stripped from the shell input as it is read and before each line is compared with word; and
- the shell reads its input right up to the first line that literally matches the resulting word, or until it hits an EOF. like, exact string match, no vibes-based fuzzy matching, no "close enough" energy. ๐ โโ๏ธ
If any character of word is quoted (peep the Quoting section later, bestie), then no additional processing happens to the shell input. none. but if none of the characters of word are quoted:
- parameter and command substitution happens;
- (escaped)
\newlines get removed; and \must be used to quote the characters\,$, and`.
The resulting document becomes the standard input. slay, that's the whole bit. ๐
<&digitโ uses the file associated with file descriptor digit as standard input. same exact situation for standard output, but with>&digit.<&-โ standard input gets closed. same for standard output using>&-.
If any of the above has a digit in front of it, then the file descriptor associated with the file is the one that digit names (instead of the default 0 or 1). for example:
... 2>&1
hooks file descriptor 2 up to the file that file descriptor 1 is currently associated with. matching set, iconic. โจ
the order you write redirections in matters, no cap. the shell evaluates them left-to-right.
for example:
... 1>xxx 2>&1
first it associates file descriptor 1 with the file xxx. then it associates file descriptor 2 with the file associated with file descriptor 1 (that is, xxx). but if you'd put the redirections in the reverse order, file descriptor 2 would be associated with the terminal (assuming file descriptor 1 had been) and file descriptor 1 would be associated with the file xxx. so yeah, sequence queen behavior. ๐
Using the terminology we introduced on the first page, under Commands: if a command is composed of several simple commands, redirection is evaluated for the entire command before it's evaluated for each simple command. like, the shell evaluates redirection for the entire list, then each pipeline within the list, then each command within each pipeline, then each list within each command. it's giving nesting dolls. ๐ช
If a command is followed by & and job control (see set -m) is not active, the default standard input for that command is the empty file, /dev/null. otherwise, the environment for the execution of a command contains the file descriptors of the invoking shell as modified by input/output specifications.
๐ File Name Generation ๐
Before a command is executed, each command word gets scanned for the characters *, ?, and [. if one of these characters shows up, the word is regarded as a pattern. the word then gets replaced with alphabetically sorted file names that match the pattern. if no file name is found that matches the pattern, the word is left unchanged โ it just stays as-is, no drama. ๐ฆ
also: the character . at the start of a file name or immediately following a /, as well as the character / itself, must be matched explicitly. them's the rules.
*โ matches any string, including the null string.?โ matches any single character.[...]โ matches any one of the enclosed characters. a pair of characters separated by-matches any character lexically between the pair, inclusive. if the first character following the opening[is a!, then any character not enclosed is matched.
Notice that all quoted characters (see below) must be matched explicitly in a filename. quoted = taken literally, periodt.
๐ Quoting ๐
The following characters have a special meaning to the shell and cause termination of a word unless quoted:
; & ( ) | ^ < > newline space tab
A character can be quoted (that is, made to stand for itself) by preceding it with a backslash (\) or inserting it between a pair of quote marks ('' or ""). during processing, the shell can quote certain characters to prevent them from taking on a special meaning. backslashes used to quote a single character get removed from the word before the command is executed. and the pair \newline is removed from a word before command and parameter substitution. bye bestie, you're not needed. ๐
All characters enclosed between a pair of single quote marks (''), except a single quote, are quoted by the shell. backslash has no special meaning inside a pair of single quotes โ it's just a guy standing there. ๐ถ a single quote can be quoted inside a pair of double quote marks (for example, "'"), but a single quote can not be quoted inside a pair of single quotes. that's the one thing you can't do, sorry. ๐
Inside a pair of double quote marks (""), parameter and command substitution occurs, and the shell quotes the results to avoid blank interpretation and file name generation. if $* is within a pair of double quotes, the positional parameters are substituted and quoted, separated by quoted spaces ("$1 $2 ..."). however, if $@ is within a pair of double quotes, the positional parameters are substituted and quoted, separated by unquoted spaces ("$1""$2" ...). yes, this distinction is real and yes, it will be on the test. ๐ญ
\ quotes the characters \, `, , (comma), and $. the pair \newlineis removed before parameter and command substitution. if a backslash precedes characters other than`, `, , (comma), $`, and newline, then the backslash itself is quoted by the shell. it's quoting the quoter. inception core. ๐
โญ Prompting โญ
When used interactively, the shell prompts with the value of PS1 before reading a command. and if at any time a newline is typed and further input is needed to complete a command, the secondary prompt (that is, the value of PS2) is issued. PS2 is that little "โฆi'm still listening" queen. ๐ซถ
๐ Environment ๐
The environment (see environ(7)) is a list of name-value pairs that gets passed to an executed program in the same way as a normal argument list. the shell interacts with the environment in several ways. on invocation, the shell scans the environment and creates a parameter for each name found, giving it the corresponding value. if the user modifies the value of any of these parameters or creates new parameters, none of these affects the environment unless the export command is used to bind the shell's parameter to the environment (see also set -a). a parameter can be removed from the environment with the unset command. so the environment seen by any executed command is composed of:
- any unmodified name-value pairs originally inherited by the shell,
- minus any pairs removed by
unset, - plus any modifications or additions โ all of which must be noted in
exportcommands.
When the shell starts in POSIX mode, all variables imported from the environment are given the export property, and the shell's internal values cannot be modified independently from the values propagated via the environment to child processes. locked in together, no separate paths. ๐
The environment for any simple-command can be augmented by prefixing it with one or more assignments to parameters. thus:
TERM=450 command
and
(export TERM; TERM=450; command)
are equivalent as far as the execution of command is concerned if command is not a Special Command. but if command is a Special Command, then
TERM=450 command
modifies the TERM variable in the current shell. different beast entirely, iykyk. ๐
If the -k flag is set, all keyword arguments are placed in the environment, even if they occur after the command name. the following example first prints a=b c and then c:
echo a=b c
a=b c
set -k
echo a=b c
c
๐ฅ Signals ๐ฅ
The INTERRUPT and QUIT signals for an invoked command are ignored if the command is followed by &. otherwise, signals have the values inherited by the shell from its parent, with the exception of signal 11 (but see also the trap command below). signal 11 stays doing its own thing, apparently. ๐ฉ
๐ธ Execution ๐ธ
Each time a command is executed, the command substitution, parameter substitution, blank interpretation, input/output redirection, and filename generation listed above are carried out. if the command name matches the name of a defined function, the function is executed in the shell process (note how this differs from the execution of shell script files, which require a sub-shell for invocation). and if the command name doesn't match the name of a defined function but does match one of the Special Commands listed below, it's executed in the shell process too.
The positional parameters $1, $2, ... are set to the arguments of the function. if the command name matches neither a Special Command nor the name of a defined function, a new process is created and an attempt is made to execute the command via exec(2). new process, new me. ๐ฆ
The shell parameter PATH defines the search path for the directory containing the command. alternative directory names are separated by a colon (:). the default path is /usr/bin:.. the current directory is specified by a null path name, which can appear immediately after the equal sign, between two colon delimiters anywhere in the path list, or at the end of the path list. if the command name contains a /, the search path is not used. otherwise, each directory in the path is searched for an executable file. if the file has execute permission but is not an a.out file, it's assumed to be a file containing shell commands, and a sub-shell is spawned to read it. a parenthesized command is also executed in a sub-shell. ๐ฃ
The location in the search path where a command was found is remembered by the shell (to help avoid unnecessary execs later). if the command was found in a relative directory, its location must be re-determined whenever the current directory changes. the shell forgets all remembered locations whenever the PATH variable is changed or the hash -r command is executed (see below). memory of a goldfish on purpose. ๐
๐ Built-in Commands ๐
The following commands are executed in the shell process. input/output redirection is permitted for these commands. file descriptor 1 is the default output location. when Job Control is enabled, additional Built-in Commands are added to the shell's environment (see the Job Control section below).
Commands marked with a + are treated specially in the following ways:
- parameter assignments that precede a special builtin command affect the shell itself.
- I/O redirections are processed after variable assignments for variables that precede the builtin command.
- errors may cause a script that contains them to abort. yeah, these ones will absolutely end your whole script. ๐ญ
In older versions of sh, parameter assignments that precede any builtin command did always affect the shell itself.
+ :โ no effect; the command does nothing. a zero exit code is returned. literally the "i'm just here so i won't get fined" of commands. ๐+ . filenameโ read and execute commands from filename and return. the search path specified byPATHis used to find the directory containing filename.[ [expr] ]โ seetestbuiltin below.alias [ options ] [alias-name[=value]...]โ thealiascommand creates, redefines or lists existing alias definitions. an alias definition provides a string value that replaces a command name when it's encountered on the command line.
Okay so the alias command in the Bourne Shell is out here doing the absolute most โ it handles temporary aliases (the POSIX ones โจ) that only affect the current execution environment, plus persistent aliases that affect all interactive shells called after a persistent alias definition got entered or modified. Two whole modes, she contains multitudes ๐
When you pass an argument in the form alias-name, alias lists the related alias on stdout. Pass alias-name=value and alias defines or redefines an alias โ or pushes an alias definition on top of an old one. Give it no argument at all and it lists every current alias definition. All of them. The whole collection ๐
Bestie, listen: alias definitions made with the alias shell built-in must be written with appropriate quoting so that they're suitable for reinput to the shell parser. Quote it properly or it does not come back, periodt.
The # commands give you a whole alternate interface for defining aliases that never touches the standard shell parser. So it doesn't require any quoting beyond the quoting that's needed for the final command line in the expanded command. Chef's kiss ๐ง
Heads up though โ the alias command was not supported in older versions of sh. Ancient behavior, we don't claim it ๐
So when you're operating on temporary aliases (that's when neither -g nor -l have been specified), alias always pushes new definitions on top of older ones. That's literally what makes those alias definitions temporary in the global aliases name space by default, exactly as the POSIX standard requires. The following options are how you modify the operation:
-aโ defines an alias definition that expands on all arguments of a command line, not only for command names. Use with care ๐ซถ-eโ lists the everlasting version of the persistent alias definitions instead of listing the currently active definitions that may have been pushed on top of the persistent definitions.-gโ define or list persistent global aliases that live in the file$HOME/.globalsand get read by interactive shells. When defining an alias with-gin effect,aliasby default modifies the current top level definition for global aliases. If there was no push operation before on the related alias, the current definition is made persistent by writing the definitions to$HOME/.globals. The option-gis not permitted if persistent global aliases are disabled (seesetcommand below).-lโ define or list persistent directory local aliases that live in the file.localsin the current directory and get read by interactive shells. When defining an alias with-lin effect,aliasby default modifies the current top level definition for local aliases. If there was no push operation before on the related alias, the current definition is made persistent by writing the definitions to.localsin the current directory. The option-lis not permitted if persistent local aliases are disabled (seesetcommand below).-pโ when defining or redefining aliases, enforce a push operation even if the option-gor-lhas been specified. In push mode, the new alias definition gets pushed temporarily on top of existing definitions instead of modifying the current definition.
When listing aliases, this option implements compatibility to bash/ksh93 and outputs aliases in a form that can be used as input to the shell to recreate the current aliases. With -p in effect in list mode, the persistent definition and all pushed definitions are listed; otherwise only the current active definitions are listed.
-rโ reload persistent aliases after removing all current aliases. If persistent aliases are disabled, the effect is the same as with callingunalias -a. No arguments are allowed with this option.-R,-raw,--rawโ output the listing in the raw format that's used in the persistent definition files$HOME/.globalsand.locals. This increases readability since the quoting needed for defining an alias with thealiascommand is omitted.
Aliases can be edited in the raw format using # commands, see the related section above ๐
Aliases are often used together with the dosh builtin to run small parameterized pseudo shell scripts. An alias that lists files in the long format and pipes the result into more(1) could be implemented like this:
alias lm='dosh '\''ls -l "$@" | more'\'' lm-alias'
๐ธ alloc
In case sh has been compiled with storage debugging support, the alloc command prints info about the current state of the storage subsystem; otherwise alloc is just a dummy command. No thoughts, empty head ๐
The alloc command was not supported in older versions of sh.
๐ฆ bg [%jobid ...]
When Job Control is enabled, the bg command gets added to the user's environment to manipulate jobs. It resumes the execution of a stopped job in the background. If %jobid is omitted, the current job is assumed. (See the Job Control section below for more detail โ it's giving main character energy.)
โญ builtin [ -dis ] [ -f lib ] [ name ... ]
The builtin command lets you manage builtin commands. Very meta of her.
When there's no name parameter and neither -d nor -f are specified, the list of builtin commands is printed. When -i is specified, only shell intrinsic commands are listed. When -s is specified, only special builtin commands are listed.
When -d is specified, each named builtin command is deleted. Special builtin commands cannot be deleted, so don't even try ๐
On platforms that allow loading dynamic libraries, -f lets you load a dynamic library that contains builtin commands.
Without -d, all name parameters are added as builtins.
The builtin command was not supported in older versions of sh. And POSIX does not require the builtin command to be supported โ she's optional, she's a bonus. Slay.
๐ + break [ n ]
Exit from the enclosing for or while loop, if any. If n is specified, break n levels. Deleting the whole stack of loops in one go ๐
๐ cd [ -L | -P ] [ argument ]
Change the current directory to argument. If arg is - the directory is changed to the previous directory. The shell parameter HOME is the default argument. The shell parameter CDPATH defines the search path for the directory containing argument. Alternative directory names are separated by a colon (:). The default path is <null> (specifying the current directory).
Note: the current directory is specified by a null path name, which can appear immediately after the equal sign or between the colon delimiters anywhere else in the path list. This is real and you will encounter it.
If argument begins with a / the search path is not used. Otherwise, each directory in the path is searched for argument.
The previous working directory is kept in the shell parameter OLDPWD, the new working directory is kept in the shell parameter PWD. The top of the directory stack gets replaced by the new working directory. Bookkeeping queen ๐
-Lโ handles the operation dot-dot (..) logically. Symbolic link components are not resolved before dot-dot components are processed, and dot-dot (..) operations are handled by removing the path component to the left of the dot-dot (..) in the supplied path or inPWD.-Pโ handles the operation dot-dot physically. Symbolic link components are resolved before dot-dot components are processed.
If both -L and -P are specified, the last one applies. If neither -L nor -P is specified, cd behaves as if -P had been specified โ except when in POSIX mode, where the default is -L. See section COMPATIBILITY below.
The options -L and -P and the special parameter - were not recognised by older versions of sh. โจ
๐ chdir [ -L | -P ] [ dir ]
chdir changes the shell's working directory to directory dir. If no argument is given, change to the home directory of the user. If dir is a relative pathname not found in the current directory, check for it in those directories listed in the CDPATH variable. And if dir is the name of a shell variable whose value starts with a /, change to the directory named by that value. Sneaky but valid ๐ฅ
๐ command [ -p ] [ -v | -V ] name [arg ...]
Without the option -v or -V, command executes name with the arguments specified by arg.
With -v or -V, name is not executed, but a description of name is printed. With -V, the output is like the output from the type built-in command but function definitions are not listed. With -v, the output is less verbose.
The option -p causes a default path to be searched that grants all POSIX commands to be found, rather than using the search path defined by the value of PATH.
Functions are not searched when trying to execute name. On top of that, if name refers to a special built-in, none of the special properties associated with the built-in commands marked with leading daggers are honored. For example, using command exec instead of exec prevents a script from terminating when an invalid redirection is specified. Lowkey important ๐ญ
The command built-in command was not supported in older versions of sh.
๐ + continue [ n ]
Resume the next iteration of the enclosing for or while loop. If n is specified, resume at the n-th enclosing loop. Keep going bestie, we're so back ๐ซถ
๐ง dirs [ -L | -P ]
Print the content of the directory stack. The top of the stack is the leftmost element, which has the logical offset 0. The next element to the right has the logical offset 1. The logical offset of a directory may be used as argument to the pushd and the popd command. If there's no directory stack, the result is the same as with calling pwd.
-Lโ if thePWDshell parameter contains an absolute pathname of the current directory that does not contain the filenames dot or dot-dot,pwdwrites this pathname to standard output, regardless of whether it contains filename components that refer to symbolic links. Otherwise, the-Loption behaves like the-Poption.-Pโ the absolute pathname written does not contain filename components that refer to files of type symbolic link.
(Yes, those two descriptions genuinely talk about pwd โ that's how the page is written, I'm just the messenger ๐)
If both -L and -P are specified, the last one applies. If neither -L nor -P is specified, pwd behaves as if -P had been specified โ except when in POSIX mode, where the default is -L. See section COMPATIBILITY below.
The dirs command was not supported in older versions of sh.
+ **export [ -p ] [ name[=value] ... ]** โ okay so the names you give it get marked for automatic export into the environment of every command that runs after this. No arguments? Then it just lists the variable names that got marked for export while the *current* shell has been running. The **-p** option makes the wordexport` get inserted in front of each name. (Heads up: when you're not in POSIX mode, variables exported from a parent shell only show up in that list if they've been exported again during the current shell's execution.) Function names do not get exported, periodt.
Real talk: the-poption was not supported in older versions ofsh, and specifying a value was not supported in older versions ofsheither. ๐
falseโ the icon that does absolutely nothing. It returns a non-zero exit code (1), which is literally its whole personality. Bestie uses it withuntilfor infinite loops. ๐
Thefalsecommand was not a builtin command in older versions ofsh.
๐ fc โ the history-editor one
fc [-r] [-e editor] [first [last]]
fc -l [-nr] [first [last]]
fc -s [old=new] [first]
The fc builtin lists โ or edits and re-executes โ commands you previously typed into an interactive sh. It's giving time travel but make it shell. โจ
In the first form, a range of commands from first to last gets selected and edited, and then the edit result gets re-executed. If the editor returns a non-zero exit status, the commands are not re-executed. ๐
โโ๏ธ
In the second form, a range of commands from first to last is listed.
In the third form, the command specified by first is re-executed.
When commands are edited or re-executed, the resulting lines are entered at the end of the history list and then re-executed by sh. The fc command that caused the editing or re-execution is not entered into the history list. Sneaky but valid. ๐ซถ
The following options are supported:
-e editorโ useeditorto edit the commands. The value in theFCEDITvariable is used as a default when-eis not specified. IfFCEDITis null or unset,edis used as the editor. (yes,ed. vintage era ๐ )-lโ list the commands rather than invoking an editor on them. The commands are written in the sequence indicated by thefirstandlastoperands and affected by-r, with each command preceded by the command number.
In this case, the fc command is entered into the history.
-nโ suppress command numbers when listing with-l.-rโ reverse the order of the commands listed or edited.-sโ re-execute the command without invoking an editor.
The following operands are supported:
first,lastโ select the commands to list or edit. The number of previous commands that can be accessed is determined by the value of theHISTSIZEvariable. The value offirstorlastor both may be one of the following:[+]numberโ a positive number representing a command number. Command numbers can be displayed with the-loption.-numberโ a negative number representing the command that was executednumberof commands previously. For example,-1is the previous command and-0is the current command.stringโ a string indicating the most recently entered command that begins with that string. If theold=newoperand is not also specified with-s, the string form of thefirstoperand cannot contain an embedded equal-sign.
If first is omitted, -15 is assumed in list mode (-l) and -1 in other cases. If 0 is used as the value for first, the whole history is selected. ๐ฐ๏ธ
old=newโ replace the first occurrence of the stringoldin the commands to be re-executed by the stringnew.
Hot tip, bestie: note that the history is an interactive feature โ commands read from scripts are not entered into the history. Scripts stay off the timeline. ๐
The fc command was not supported in older versions of sh, it is an artefact from ksh from a time when ksh still needed an external editor to modify the history.
The interactive history implementation that is used in this version of the Bourne Shell already supported fully integrated editing features in the command line in 1984 and uses concepts from 1982 that make fc a deprecated feature for editing commands in the history. fc is required by a POSIX feature named user portability, it should be avoided in favor of the history command. ๐ซก
๐ฆ find
find file1 ... filen [find_expr]
The find command is available as a builtin command that is implemented via libfind. It's giving main character energy in the builtin lineup.
The find implementation of this shell includes primary operators called -call and -calldir that allow directly calling back commands into the shell. Since this does not need to create a new process, it is much faster than the -exec primary. Speed demon fr fr ๐ฅ
In the Bourne Shell, the command following the -call primary is evaluated similar to the eval(1) command in case the first argument to -call does not contain a shell variable reference, and similar to sh -c command call argument... or the dosh(1) builtin in case there is a variable reference.
The eval(1) mode is triggered with simple commands that do not contain variable references:
find . -call echo {} \;
The dosh(1) mode is triggered with commands that contain variable references:
find . -call 'test -d "$1" && echo dir: "$1"' {} \;
The shell variable $0 is set to the value call in this case and the equivalent find command using -exec would be:
find . -exec sh -c 'test -d "$1" && echo dir: "$1"' call {} \;
You may like to try both commands to see the performance win using the -call find(1) primary. Do it, you'll be obsessed. ๐
See sfind(1) for more information.
Thefindcommand was not supported as a builtin command in older versions ofsh.
๐ fg
fg [%jobid ...]
When Job Control is enabled, the fg command is added to the user's environment to manipulate jobs. This command resumes the execution of a stopped job in the foreground and also moves an executing background job into the foreground. If %jobid is omitted, the current job is assumed. (See Job Control section below for more detail.) Bringing your jobs back to the front where they belong ๐ซถ
๐ธ getopts
getopts optstring name [arg...]
Use this in shell scripts to support command syntax standards (see Intro(1)). This command parses positional parameters and checks for legal options. See getoptcvt(1) for usage and description. Option-parsing slay โจ
The getopts builtin command parses its args or the global args of the current shell, using optstring as the option definition. Each time it is invoked, it places the next option character into the variable name and the index of the next argument to be processed into OPTIND. Whenever the shell or a shell script is invoked, OPTIND is initialized to 1. Calling getopts repeatedly causes one option to be retrieved per call. It's giving one-at-a-time, no cap.
When an option requires an option-argument, getopts places it in the shell variable OPTARG.
If an illegal option is encountered, ? is placed in name. If optstring starts with a colon and a required option-argument is missing, a colon is placed in name.
When the end of options is encountered, getopts exits with a non-zero exit status. The special arg -- can be used to delimit the end of the options. Bye felicia ๐
optstring must contain the option letters the command using getopts recognizes. If a letter is followed by a colon, the option is expected to have an argument, or group of arguments, which must be separated from it by white space. ๐
Quick vibe check before we get into the flags: unless optstring starts with a colon, getopts prints an error message on the standard error when it encounters an option letter not included in optstring.
If optstring starts with a +, options in the form +o, +long-option or ++long-option are recognised and the name shell variable gets a value with a leading + in case an option in the form +o, +long-option or ++long-option is used.
If more than one flag character from :, + or () is used in optstring, () needs to be last. Order matters bestie, don't come for me.
getopts supports one or more long options as an alias to a short option. You must enclose each long option equivalent in parentheses, as follows:
getopts "f:(file)(input-file)o:(output-file)"
In the above example, both --file and --input-file are the equivalent of -f, and --output-file is the equivalent of -o. Look at that little family tree ๐
If optstring starts with (), getopts supports long options with a single dash. Long options with a single dash have been introduced with Multics and appeared on UNIX around 1980, see e.g. kill(1). history lesson AND syntax, we love a multitasker โจ
If a long name argument follows a single dash and cannot be identified as a long option, it is retried as a combination of single character letters. To suppress error messages, the optional initial colon in optstring must precede the ():
getopts ":()f:(file)(input-file)o:(output-file)"
In the above example, -file, --file, -input-file, --input-file are the equivalent of -f, and -output-file and --output-file is the equivalent of -o. Error messages from getopts are suppressed and a colon is placed in name when an option argument for an option like -f is missing.
getopts also supports one or more long options with no related short option. You must set up a decimal numerical value >= 256 between two question mark signs in place of an option letter in optstring:
getopts "f:(file)(input-file)?900?:(output-file)"
In the above example, the long option --output-file is associated to the integer value 900 and in case the option --output-file was specified, string 900 is set up as the value for name. iconic little numeric moment, no cap
hash [ -r ] [ name ... ]
For each name, the location in the search path of the command specified by name is determined and remembered by the shell. The -r option causes the shell to forget all remembered locations. If no arguments are given, information about remembered commands is presented. Hits is the number of times a command has been invoked by the shell process. Cost is a measure of the work required to locate a command in the search path. If a command is found in a "relative" directory in the search path, after changing to that directory, the stored location of that command is recalculated. Commands for which this are done are indicated by an asterisk (*) adjacent to the hits information. Cost is incremented when the recalculation is done. Certified fresh garbage-collection behavior ๐ซถ
history [-nr] [first [last]]
Print the current command history. The history command is only supported if sh was compiled with support for history editing. iykyk
If no command or command range is specified, the last 16 commands are listed. If only first with a value of 0 is specified, the whole history is printed.
The following options are supported:
-nโ Suppress command numbers when listing with-l.-rโ Reverse the order of the commands listed or edited.
The history command was not supported in older versions of sh. POSIX does not require the history command to be supported.
jobs [-p|-l] [%jobid ...]
jobs -x command [arguments]
Reports all jobs that are stopped or executing in the background. If %jobid is omitted, all jobs that are stopped or running in the background are reported. (See Job Control section below for more detail.) scroll down bestie, the lore is there ๐
kill [ -sig | -s sig ] [ pid ] [ %job ] ...
kill -l [ sig ] ...
Sends either the TERM (terminate) signal or the specified signal to the specified jobs or processes. Signals are either given by number or by names (as given in signal.h(3HEAD) stripped of the prefix SIG with the exception that SIGCHD is named CHLD). If the signal being sent is TERM (terminate) or HUP (hangup), then the job or process is sent a CONT (continue) signal if it is stopped. The argument job can be the process id of a process that is not a member of one of the active jobs. See Job Control section below for a description of the format of job. In the second form, kill -l, the signal numbers and names are listed. The optional sig argument list may contain signal numbers or $? exit values that refer to a program terminated by a signal. (See kill(1)).
Signal numbers are not portable across platforms, except for the following:
0โ No signal1โHUP2โINT3โQUIT6โABRT9โKILL14โALRM15โTERM
โ ๏ธ not portable, do NOT assume, I'm literally begging you โ ๏ธ The kill option -s and kill -l with arguments was not supported in older versions of sh.
killpg [ -sig | -s sig ] [ pgrp ] [ %job ] ...
killpg -l [ sig ] ...
Sends either the TERM (terminate) signal or the specified signal to the specified jobs or processgroups. See kill for more information.
The killpg command was not supported in older versions of sh.
limit [-HS] [resource [limit]]
limit is a csh compatibility variant of the ulimit command. throwback era fr
If no option is supplied, the soft limits are modified and both, hard and soft limits are displayed.
If no argument is supplied, all limits are displayed.
The limit command was not supported in older versions of sh.
local [ name[=value] ... ]
The given names are marked for local scope to the function from where local is called. The scope is effective for the rest of the function and its children or until local is called again with the same variable name. The local variable is created with the same content and attributes as the current variable. If the local variable is exported, it's local value is seen by child processes called from a function. If no arguments are given, variable names that have been marked for local scope are listed. It is an error to use local when not within a function. read that last sentence again bestie, it's a whole thing
The local command was not supported in older versions of sh.
login [ argument ... ]
Equivalent to exec login argument.... See login(1) for usage and description.
map
map -r
map map_from map_to [ comment ]
map -u map_from
Handle history editor input mapping. Input mapping in the history editor is automatically managed via TERMCAP for the cursor keys and via manual maps in the file $HOME/.bshmap. The map command is only supported if sh was compiled with support for history editing.
If the map command is called without arguments, it prints the current input mapping.
If map is called with -r, all current mappings are removed and the default mapping is reloaded from TERMCAP and $HOME/.bshmap. Call map -r after changing TERM, TERMCAP or TERMPATH or when a change was made in the file $HOME/.bshmap.
It map is called with two or three arguments, a new mapping is set up. The parameters map_from and map_to may need quoting to be correctly passed to the mapping engine.
Call map -u map_from to unmap an existing mapping. The parameter map_from needs quoting for both the input mapper and the shell to be correctly passed to the mapping engine.
For more information and for escape sequences known by the mapper see the section History Editing Input Mappings below. the lore continues, keep scrolling ๐ง
The map command was not supported in older versions of sh. POSIX does not require the map command to be supported.
newgrp [ argument ]
Equivalent to exec newgrp argument. See newgrp(1) for usage and description.
pgrp [%jobid ...]
Print the process groups and session groups for the specified processes or jobs. The argument job can be the process id of a process that is not a member of one of the active jobs. See Job Control section below for a description of the format of job. If %jobid is omitted, the process group for the current shell and the process group for the tty connected to stdin of the pgrp command is printed.
If the process group id equals the process id, the process is a process group leader. If the session group id equals the process id, the process is a session group leader. main character energy, literally ๐
The pgrp command was not supported in older versions of sh. POSIX does not require the pgrp command to be supported.
popd [ -L | -P ] [ -offset ]
Calling popd without argument removes the current top directory stack element from the directory stack and then performs a cd to the new top directory stack element. Calling popd with an offset argument removes the current the top directory stack element from the directory stack, then removes the directory stack element named by offset from the current directory stack and then makes it the new top directory stack element and performs a cd to this directory. The new directory name is always printed as it was not given as an argument. See dirs for an explanation of offset. it's giving stack girlie ๐
-Lโ Handles the operation logically. Symbolic link components are not resolved before thePWDshell parameter is assigned the new value.-Pโ Handles the operation physically. Symbolic link components are resolved before thePWDshell parameter is assigned the new value.
If both -L and -P are specified, the last one applies. If neither -L nor -P is specified, cd behaves as if -P had been specified, except when in POSIX mode where the default is -L. See section COMPATIBILITY below. yes this is the same rule as cd, they're siblings โจ
The popd command was not supported in older versions of sh.
printf format [argument ...]
The printf command writes formatted operands to the standard output. The argument operands are formatted under control of the format operand. The format operand is treated like a printf(3) format string and the escape sequences '\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\' and '\ddd', where ddd is one to three octal digits, are expanded as if they were in a C string. classic printf behavior, we stan ๐
Okay so let's keep going with printf โ because she's got even more tricks up her sleeve ๐
Besides the format specifiers %c, %s, %d, %i, %o, %u, %x, %X, %e, %E, %f, %F, %g, %G, the format %b is also supported โจ The integers are handled internally as intmax_t so you never get range problems โ even though only the standard int type specifiers are supported in the format operand. And %b? Treated like %s, except the escape sequences in the argument string get expanded, exactly like with the echo command. Iconic behaviour, no cap.
Field width and precision can be specified either numerically in the format operand, or via the '*' format specifier and its related arguments. Flexible queen ๐
The printf(3) flag characters '+', ' ', '#' and '0' are supported too.
The format strings %n$ and *m$, where n or m are decimal integers in the range 1 .. maxargs, let you specify the position in the parameter list. See printf(3) for more info, iykyk ๐
The format operand gets reused as often as necessary to satisfy the argument operands ๐ If the format operand has more format specifiers than argument operands were specified, string formats are treated as if an empty string had been supplied, and integer arguments are treated as if a 0 had been supplied. She's just filling in the blanks bestie.
Note that POSIX neither requires support for floating point numbers nor support for the%n$and*m$format. So don't come for her if some other shell doesn't have the range ๐ญ
Fun fact: the printf command was not a builtin command in older versions of sh. We've been blessed since then โจ
๐ซ pushd
pushd [ -L | -P ] [ name ]
pushd [ -L | -P ] [ -offset ]
pushd is basically cd's clingier bestie ๐ซถ โ it's similar to the cd command, but it keeps the previous working directory on the directory stack. Obsessed.
If -offset is used instead of a directory name, it exchanges the content of the top directory stack element with the directory stack element named by offset, and then performs a cd to the new top directory stack element. If the new directory stack has more than one element, it gets printed ๐ธ See dirs for an explanation of offset.
-Lโ Handles the dot-dot (..) operation logically. Symbolic link components are not resolved before dot-dot components are processed, and dot-dot (..) operations are handled by removing the path component to the left of the dot-dot (..) in the supplied path or inPWD.-Pโ Handles the dot-dot operation physically. Symbolic link components are resolved before dot-dot components are processed.
If both -L and -P are specified, the last one applies ๐ If neither -L nor -P is specified, pushd behaves as if -P had been specified โ except when in POSIX mode, where the default is -L. See section COMPATIBILITY below.
The pushd command was not supported in older versions of sh. She's new gen ๐
๐ pwd
pwd [ -L | -P ]
Prints the current working directory as an absolute pathname that does not contain the filenames dot (.) or dot-dot (..). See pwd(1) for usage and description. Also, the current working directory is kept in the shell parameter PWD ๐
-Lโ If thePWDshell parameter contains an absolute pathname of the current directory that does not contain the filenames dot or dot-dot,pwdwrites this pathname to standard output, regardless of whether it contains filename components that refer to symbolic links. Otherwise, the-Loption behaves like the-Poption.-Pโ The absolute pathname written does not contain filename components that refer to files of type symbolic link.
If both -L and -P are specified, the last one applies โญ If neither -L nor -P is specified, pwd behaves as if -P had been specified โ except when in POSIX mode, where the default is -L. See section COMPATIBILITY below.
The options -L and -P were not recognised by older versions of sh ๐
๐ฆ read
read [ -r ] [ name ... ]
One line is read from standard input, and using the internal field separator, IFS (normally space or tab), to delimit word boundaries, the first word is assigned to the first name, the second word to the second name, and so forth โ with leftover words all getting dumped onto the last name ๐ญ (she's carrying the whole team fr).
Lines can be continued using \newline. Characters other than newline can be quoted by preceding them with a backslash. These backslashes are removed before words are assigned to names, and no interpretation is done on the character that follows the backslash. If name is omitted, then REPLY is used as the default name ๐ The exit code is 0, unless an EOF is encountered.
-rโ Do not treat a backslash character in any special way. Consider each backslash to be part of the input line. The option-rwas not supported in older versions ofsh.
Omitting the name parameter of the read command was also not supported in older versions of sh. Genuinely a glow-up โจ
๐ + readonly
+ readonly [ -p ] [ name[=value] ... ]
The given names are marked readonly, and the values of these names cannot be changed by subsequent assignment ๐ If no arguments are given, a list of all readonly names is printed. The -p option causes the word readonly to be inserted before each name.
The option -p was not supported in older versions of sh. Specifying a value was not supported in older versions of sh either ๐ซถ
๐ repeat
repeat [ -c count ] [ -d delay ] command [ args ]
The command command is executed repeatedly, as if it was called via eval ๐ If the -c option is present, command is repeated count times โ otherwise execution is repeated forever (yes, forever forever ๐). If the -d option is present, sh waits delay seconds before command is executed again; otherwise there's no delay between executions.
If the command command is terminated by a signal, or if the exit code of command is nonzero, the whole repeat command is terminated. She does not keep going, bestie.
The repeat command was not supported in older versions of sh. POSIX does not require the repeat command to be supported. She's built different ๐
๐ง + return
+ return [ n ]
Causes a function or . script to return to the invoking script with the return value specified by n. If n is omitted, the return status is that of the last command executed ๐
The return command did not support terminating . scripts in older versions of sh. Fixed that for you ๐
๐ savehistory
savehistory
Saves the current history in the file $HOME/.history. That's it, that's the whole command ๐ธ
The savehistory command was not supported in older versions of sh.
โญ + set
+ set [ -abCefhkmntuvxP [ -o [ option ]] [ argument ... ] ]
The set command supports the following options, and yes, there are a lot of them โ grab a snack ๐:
-aโ Mark variables which are modified or created for export.-bโ Prints job completion messages as soon as a background job changes state, rather than waiting for the next prompt. This option is currently without effect ๐ญ The option-bwas not supported in older versions ofsh.-Cโ Prevents redirection (>) from truncating existing files. Files that are created are opened with theO_EXCLmode. Requires>|to truncate a file when turned on ๐ฅ The option-Cwas not supported in older versions ofsh.-eโ Exit immediately if a command exits with a non-zero exit status. The shell however does not exit if the command that fails is part of the command list immediately following awhileoruntilkeyword, if it is part of the test following theiforelifreserved words, if it is part of a command executed in a&&or||list except the command that is the final command in that list, if it is not the last command in a pipeline, or if the exit value of a command is being inverted with!๐ฎโ๐จ If a trap onERRis set, it is executed before the shell exits.-fโ Disable file name generation.-hโ Locate and remember function commands as functions are defined (function commands are normally located when the function is executed).-kโ All keyword arguments are placed in the environment for a command, not just those that precede the command name.-mโ Switch job control mode on. All jobs are run in their own process groups. See section Job Control (jsh) below. On systems with job control, this flag is turned on automatically for interactive shells ๐ The option-mwas not auto-enabled for interactive shells in older versions ofsh.-nโ Read commands but do not execute them.
Setting -n in an interactive shell is ignored, as this could not be undone and the shell could not even be terminated anymore ๐ Genuinely a trap, bestie.
-tโ Exit after reading and executing one command.-o[option] โ If option is not specified, list the current option setting to stdout; when invoked with+oinstead of-o, the output is written in a format that's suitable to reinput to the shell to restore the current setting ๐ When invoked with+oand with an option argument, the related option is cleared. The+ooption may be repeated to enable or disable multiple options. The value of option must be one of the following:allexportโ same energy as-a, literally identical.aliasowner=nameโ sets an alternate trusted owner for the files$HOME/.globalsand.locals๐ซถ. By default the shell just straight-up ignores alias files if they're not owned by the current shell user (security slay ๐ ). This option lets you set up a different file owner that gets accepted anyway. Set the alternate owner to the empty string and the whole feature is disabled. periodt.bgniceโ all background jobs run at a lower priority. This is the default in interactive mode, so like, it's already the vibe.errexitโ equivalent to-e.fdpipeโ turns on the extended pipe syntax that lets you have a pipe output file descriptor number in front of the pipe sign (|), e.g.2|for a pipe from stderr ๐ญ๐ฅ. Highly recommended to putset -o fdpipeinto the file$HOME/.shrcso interactive shells get the extended pipe syntax by default. Scripts that like to use this feature need to enable it themselves, no cap.fullexitcodeโ do not mask the exit code with0xFFwhen expanding$?. This gives you access to the full 32 bits from the child's exit code via$?on all modern operating systems that supportwaitid(2). Settingfullexitcodeis needed to evaluateexitcode mod 256 == 0in conditional expressions as non-zero exit code. it's giving precision ๐globalaliasesโ enables/disables persistent global aliases that are read from the file$HOME/.globals. Changing the state for this option first removes all current global aliases. If the new state is on, the persistent global aliases are loaded. ๐ฆglobskipdotโ if set, the entries.and..are skipped and not shown in globbing results. If not set, the entries.and..are always returned, even when they're not part of thereaddir(3)results. The shell flagglobskipdotis enabled by default โจ.hashallโ equivalent to-h.hashcmdsโ enable hash commands, see section#commands above ๐.hostpromptโ set thePS1value tohostname uname> ''if it was not yet changed from the default value. cute prompt glow-up ๐ignoreeofโ the POSIX variant of telling the shell not to exit on EOF; the commandexitmust be used instead. The original method of the history editor introduced in 1984 is to setIGNOREEOF=on, see section Parameter Substitution for more info. If the parameterIGNOREEOF=onwas set andignoreeofis off, EOF is still ignored. so stubborn, we love her ๐interactiveโ equivalent to-i.keywordโ equivalent to-k.localaliasesโ enables/disables persistent directory local aliases that are read from the file.localsin the current directory. Local aliases are specific to the current working directory ๐. Changing the state for this option first removes all current local aliases. If the new state is on, the persistent local aliases are loaded from the current directory.monitorโ equivalent to-m.noclobberโ equivalent to-C.noexecโ equivalent to-n.noglobโ equivalent to-f.notifyโ equivalent to-b.nounsetโ equivalent to-u.onecmdโ equivalent to-t.pfshโ equivalent to-P.posixโ sets the behavior of the Bourne Shell to POSIX mode, where its default differs from the POSIX standard ๐๏ธ. When in POSIX mode, it's disallowed to use^as the pipe symbol, support fortest -twithout a parameter is switched off, and the default for directory operations is set to-L. If this option is enabled at startup or later, all shell variables from the imported environment are given the export property. If this option is switched off, the export property is switched off for all imported variables that have not yet been modified. POSIX mode is enabled by default if the executable path of the shell equals a compiled in value, e.g./usr/xpg4/bin/sh.privilegedโ equivalent to-p.promptcmdsubstโ apply command substitution and arithmetic substitution to the variablesPS1,PS2andPS4. By defaultpromptcmdsubstis switched off to avoid security problems caused by imported variables โ ๏ธ. Ifpromptcmdsubstis switched on, the variablesPS1,PS2andPS4are reset to their default values for security reasons. Note that POSIX only requires parameter substitution, but no command substitution or arithmetic substitution forPS1,PS2andPS4. iykyk.restrictedโ equivalent to-r.stdinโ equivalent to-s.timeโ switch on automatic timing for commands โฑ๏ธ. The variableTIMEFORMATmay be used to control the output format.verboseโ equivalent to-v.vedโ allow shell command line editing using the built inved(1)editor.viโ allow shell command line editing using the built invieditor. The Bourne Shell currently does not allow one to set thevimode for any type of terminal ๐ซ.xtraceโ equivalent to-x.
The option -o was not supported in older versions of sh. (throwback lore ๐)
-uโ treat unset variables as an error when substituting ๐ค.-vโ print shell input lines as they are read.-xโ print commands and their arguments as they are executed.-Pโ switch profile mode on. In this mode, the shell runs privileged programs automatically in privileged mode ๐. Seepfexec(1)for further information. This feature is only supported on Solaris 10 and above. The option-Pwas not supported in older versions ofsh.-โ clear the-vand-xoption.--โ stop option processing. Further parameters are handled as normal args even when they start with a-. If no arguments follow this delimiter, then the positional parameters are unset.
Older versions ofshdid not allow unsetting the positional parameters withset --. ๐
Using + rather than - causes these flags to be turned off. These flags can also be used upon invocation of the shell. The flags -c, -i, -p, -r and -s can only be set upon invocation of the shell โ they cannot be modified using the set command, sorry bestie ๐. The current set of flags can be found in $-. The remaining arguments are positional parameters and are assigned, in order, to $1, $2, ...
If no arguments are given, the names and values of all variables are printed. When in POSIX mode (via set -o posix), only shell variables are printed; otherwise functions are listed amongst the shell variables. ๐ธ
+ shift [ n ]
The positional parameters from $n+1 ... are renamed $1 ... . If n is not given, it is assumed to be 1. shuffle time ๐
stop pid ...
Halt execution of the process number pid. (see ps(1)). ๐
suspend
Stops the execution of the current shell (but not if it is the login shell). nap time for the main character, but the login shell stays awake ๐ด
test [expr]
Evaluate conditional expressions. See test(1) for usage and description. If the value of the expression expr is true then test returns zero exit status; otherwise, a non zero exit status is returned. test returns a non zero exit status if there are no arguments. โจ
The following primaries are used to evaluate a condition:
-bfile โ true if file exists and is a block special file ๐งฑ-cfile โ true if file exists and is a character special file.-Cfile โ true if file exists and is a contiguous file. bestie pls note:-Cwas not supported in older versions ofsh.-dfile โ true if file exists and is a directory ๐-Dfile โ true if file exists and is a door ๐ช (yes, door door).-Dwas not supported in older versions ofsh.-efile โ true if file exists.-ewas not supported in older versions ofsh.-ffile โ true if file exists and is a regular file. plot twist: if Bourne Shell girlies put/usr/ucbbefore/usr/binin theirPATHenvironment variable, thentestreturns true if file exists and is (not-a-directory).-gfile โ true if file exists and its set group ID flag is set.-Gfile โ true if file exists and its group matches the effective group id of this process.-Gwas not supported in older versions ofsh.-hfile โ true if file exists and is a symbolic link ๐-kfile โ true if file exists and has its set sticky bit set.-Lfile โ true if file exists and is a symbolic link.-nstring โ true if the length of string is non-zero.-Nfile โ true if file exists and its modification time is greater than its access time.-Nwas not supported in older versions ofsh.-ooption โ true if the option named option is on.-o ?option โ true if the option named option is a valid option name.-owas not supported in older versions ofsh.-Ofile โ true if file exists and its owner matches the effective user id of this process.-Owas not supported in older versions ofsh.-pfile โ true if file exists and is a named pipe (FIFO) ๐ฅค-Pfile โ true if file exists and is an event port.-Pwas not supported in older versions ofsh.-rfile โ true if file exists and is readable ๐-sfile โ true if file exists and has a size greater than zero.-Sfile โ true if file exists and is a socket ๐-Swas not supported in older versions ofsh.-t[file-descriptor] โ true if the file whose file descriptor number is file-descriptor is open and is associated with a terminal ๐ฅ๏ธ. If file-descriptor isn't specified,1is used as a default value. heads up: when in POSIX mode (viaset -o posix), file-descriptor must always be specified.-ufile โ true if file exists and its set user ID flag is set.-wfile โ true if file exists and is writable โ๏ธ-xfile โ true if file exists and is executable. True indicates only that the execute flag is on. If file is a directory, true indicates that file can be searched.-zstring โ true if the length of string is zero.file1 -ef file2โ true if file1 and file2 exists and refer to the same file.-efwas not supported in older versions ofsh.file1 -nt file2โ true if file1 exists and file2 does not, or file1 is newer than file2.-ntwas not supported in older versions ofsh.file1 -ot file2โ true if file2 exists and file1 does not, or file1 is older than file2.-otwas not supported in older versions ofsh.
stringโ true if string is not the null string โจs1 = s2โ true if the strings s1 and s2 are identical.s1 != s2โ true if the strings s1 and s2 are not identical ๐n1 -eq n2โ true if the integers n1 and n2 are algebraically equal.n1 -ne n2โ true if the integers n1 and n2 are not algebraically equal.n1 -gt n2โ true if the integer n1 is algebraically greater than the integer n2.n1 -ge n2โ true if the integer n1 is algebraically greater or equal to the integer n2.n1 -lt n2โ true if the integer n1 is algebraically less than the integer n2.n1 -le n2โ true if the integer n1 is algebraically less or equal to the integer n2.
The primaries above may be combined with the following operators, bestie โ this is where it gets โจspicyโจ:
( expr )โ bracketing to group precedence ๐ซ!โ unary negation operator.-aโ binary and operator. The-abinary primary is left associative and has higher precedence than the-obinary primary.-oโ binary or operator. The-obinary primary is left associative.
The algorithm for determining the precedence of the operators and the return value that is generated is based on the number of arguments presented to test. (However, when using the [...] form, the right-bracket final argument is not counted in this algorithm. iykyk ๐
)
In the following list, $1, $2, $3 and $4 represent the arguments presented to test as condition, condition1, or condition2.
- 0 arguments: exit false (
1). - 1 argument: exit true (
0) if$1is not null. Otherwise, exit false. - 2 arguments:
- If
$1is!, exit true if$2is null, false if$2is not null. - If
$1is a unary primary, exit true if the unary test is true, false if the unary test is false. - Otherwise, produce unspecified results ๐ฌ
- If
- 3 arguments:
- If
$2is a binary primary, perform the binary test of$1and$3. - If
$1is!, negate the two-argument test of$2and$3. - If
$1is(and$3is), perform the unary test of$2. - Otherwise, produce unspecified results.
- If
- 4 arguments:
- If
$1is!, negate the three-argument test of$2,$3, and$4. - If
$1is(and$4is), perform the two-argument test of$2and$3. - Otherwise, the results are unspecified.
- If
๐จ bestie, listen to me: scripts should be careful when dealing with user-supplied input that could be confused with primaries and operators. Unless the application writer knows all the cases that produce input to the script, invocations liketest "$1" -a "$2"should be written astest "$1" && test "$2"to avoid problems if a user supplied value such as$1is set to!and$2is set to the null string. That is, in cases where maximal portability is of concern, replacetest expr1 -a expr2withtest expr1 && test expr2, and replacetest expr1 -o expr2withtest expr1 || test expr2. But notice that, intest,-ahas higher precedence than-o, while&&and||have equal precedence in the shell. ๐ญ
+ times
Print the accumulated user and system times for processes run from the shell โฑ๏ธ
The first line lists the shell's user and system times, the second line lists the children's user and system times.
+ trap [ [argument] n [ n2 ... ] ]
+ trap -p [ n [ n2 ... ] ]
The command argument is to be read and executed when the shell receives numeric or symbolic signal(s) (n) ๐ฅ (Note: argument is scanned once when the trap is set and once when the trap is taken.) Trap commands are executed in order of signal numbers of the corresponding symbolic names. Any attempt to set a trap on a signal that was ignored on entry to the current shell is ineffective.
If argument is absent, all trap(s) n are reset to their original values.
If argument is the null string, this signal is ignored by the shell and by the commands it invokes.
If n is 0 or EXIT, the command argument is executed on exit from the shell.
If n is ERR, the command argument is executed if a command terminates with a non-zero exit code. The ERR command is however not executed on the same conditions that do not cause the shell to exit when the errexit (-e) option is set.
The trap command with no arguments prints a list of commands associated with each signal number.
If argument is -, all trap(s) n are reset to their original values.
If the option -p is present, all signals from the argument list (or all signals if further arguments are absent) are printed even when they are currently set to the default. This permits to restore the whole trap state by using:
old_traps=$(trap -p)
trap "some commands" INT QUIT
...
eval "$old_traps"
๐ The shell does not produce a diagnostic message in case that a command is set up for uncatchable signals likeSIGKILLorSIGSTOP.
The - argument was not supported in older versions of sh.
The option -p was not supported in older versions of sh.
The trap name ERR was not supported in older versions of sh and is not part of the POSIX standard.
true
The true builtin does nothing. A zero exit code is returned. Used with while for infinite loops ๐ (main character energy tbh)
The true command was not a builtin command in older versions of sh.
type [ -F ] [ name ... ]
For each name, indicate how it would be interpreted if used as a command name ๐ If the option -F is specified with no arguments, all defined functions are listed. type displays information about each operand identifying the operand as a shell built-in, shell intrinsic, function, alias, hashed command, or keyword, and where applicable, may display the operand's path name. The meaning is as follows:
โฆand hereโs the command-type lore, continued: ๐
- shell built-in โ a normal command thatโs built into the shell. Some of these lowkey do not need to be built in at all; theyโre usually in this group because they were built in for historical reasons or because theyโre an extension to the current POSIX standard. โจ
- special shell built-in โ a command built into the shell that gets special treatment. This type needs to be built in to get the desired result. no cap.
- shell intrinsic โ also a command built into the shell, and again it needs to be built in to get the desired result. ๐ง
- global alias โ a global alias that gets expanded in any directory. ๐
- local alias โ a local alias thatโs bound to the current directory and expanded only there. ๐
- function โ a function defined in this shell. ๐ซถ
- keyword โ a keyword in the syntax of this shell. ๐
- command โ an external command identified by its path name. ๐ฃ๏ธ
- hashed command โ an external command that already went through path name search and hashing. #beenThere
๐ฅ ulimit ๐ฅ
ulimit [ [-HS] [-a | -bcdefiklLmMnoPqrRstuvw] ]
ulimit [ [-HS] [resource-option] ] limit
ulimit prints or sets hard or soft resource limits. These limits are described in getrlimit(2). ๐ง
If limit is not present, ulimit prints the specified limits. Any number of limits can be printed at one time. The -a option prints all limits.
If limit is present, ulimit sets the specified limit to limit. The string unlimited requests that the current limit, if any, be removed. Any user can set a soft limit to any value less than or equal to the hard limit. Any user can lower a hard limit. Only a user with appropriate privileges can raise or remove a hard limit. See getrlimit(2). ๐
The -H option specifies a hard limit. The -S option specifies a soft limit. If neither option is specified, ulimit sets both limits and print the soft limit.
The following options specify the resource whose limits are to be printed or set. If no option is specified, the file size limit is printed or set.
-bโ maximum size of socket buffer usage in bytes-cโ maximum core file size (in 512-byte blocks)-dโ maximum size of data segment or heap (in kbytes)-eโ maximum scheduling priority-fโ maximum file size (in 512-byte blocks)-iโ maximum number of pending signals-kโ maximal number of kqueues for this user ID-lโ maximum size of locked memory (in kbytes)-Lโ maximum number of file locks-mโ maximum resident set size (in kbytes)-Mโ address space limit (in kbytes), usually an alias for-v-nโ maximum file descriptor plus 1-oโ maximal number of process-shared locks for this user ID-Pโ maximum number of pseudo ttys-qโ maximum number of POSIX message queues-rโ maximum realtime priority-Rโ maximum realtime quantum (in usec)-sโ maximum size of stack segment (in kbytes)-tโ maximum CPU time (in seconds)-uโ maximum number of child processes-vโ maximum size of virtual memory (in kbytes)-wโ maximum size of swap (in kbytes)
Not all resources are supported on all platforms. To get a list of all resources available on the current platform, call ulimit -a. ๐ซก
Run the sysdef(8) command to obtain the maximum possible limits for your system. The values reported are in hexadecimal, but can be translated into decimal numbers using the bc(1) utility. See swap(8). ๐งฎ
As an example of ulimit, to limit the size of a core file dump to 0 Megabytes, type the following:
ulimit -c 0
๐ญ umask ๐ญ
umask [ -S ] [ mask ]
The user file-creation mask is set to mask (see umask(1)). The mask may either be an octal number or a symbolic notation (see chmod(1)). If the symbolic notation for mask starts with a - sign, it must be preceded with -- to keep it from being interpreted as an option. The command umask -- -w sets the file-creation mask so that subsequently created files have all their write bits cleared. ๐
If mask is omitted, the current value of the mask is printed.
Do not use a symbolic mask or -S in Bourne Shell scripts that should be portable to older revisions.
-Sโ Print the current file-creation mask in symbolic form. The output is suitable as argument for theumaskcommand.
The symbolic mode was not supported in older versions of sh.
๐งน unalias ๐งน
unalias [ options ] [alias-name...]
The unalias command removes existing alias definitions. ๐๏ธ
The unalias command in the Bourne Shell supports temporary aliases (POSIX aliases) that affect only the current execution environment as well as persistent aliases that affect all interactive shells that are called after a persistent alias definition was entered or modified.
The unalias command was not supported in older versions of sh.
When operating on temporary aliases (i.e. when neither -g nor -l have been specified), all alias definitions for a specified alias-name are popped from the existing global definitions. No alias definition for the specified alias-name remains active, but the file with persistent alias definitions is not touched. This makes unalias compatible to the POSIX standard and able to support persistent aliases at the same time. The following options may be used to modify operation:
-aโ Remove all alias definitions from the current shell execution environment. No arguments are permitted with this option. As the persistent definitions are not touched, the persistent aliases may be restored by callingalias -r.-gโ Pop a single alias definition foralias-namefrom the global aliases. If the related alias definition is the last foralias-name(usealias -p -g alias-nameto verify), remove it from the persistent global aliases that are stored in the file$HOME/.globalsand read by interactive shells.-lโ Pop a single alias definition foralias-namefrom the local aliases. If the related alias definition is the last foralias-name(usealias -p -l alias-nameto verify), remove it from the persistent local aliases that are stored in the file.localsin the current directory and read by interactive shells.-pโ When removing aliases, enforce a pop all operation even if the option-gor-lhas been specified. In pop all mode, all alias definitions for a specifiedalias-nameare popped from the existing definitions. No alias definition for the specifiedalias-nameremains active, but the file with persistent alias definitions is not touched.
๐งผ unset ๐งผ
+ unset [ -f | -v ] [ name ... ]
For each name, remove the corresponding variable or function value. Readonly variables cannot be unset. If the option -v is used, only variables will be unset. If the option -f is used, only functions will be unset. ๐
The options -f and -v have not been supported in older versions of sh.
โณ wait โณ
wait [ n ... ]
Wait for your background process whose process id is n and report its termination status. The process identifier n may either be a UNIX process id or a shell job id. See Job Control (jsh) section below for information on shell job ids. ๐ฐ๏ธ
The return code of wait is the exit code of the last process from the argument list that has successfully been waited for, or 127 / NOTFOUND in case that the argument refers to a nonexisting process.
If n is omitted, all your shellโs currently active background processes are waited for and the return code is zero.
See the shell variables $?, $/, ${.sh.code}, ${.sh.codename}, ${.sh.pid}, ${.sh.status}, ${.sh.termsig} in the section Parameter Substitution above. ๐ซถ
๐ฎ Job Control (jsh) ๐ฎ
When the shell is invoked as jsh, when the shell is invoked as interactive shell or after set -m was called, Job Control is enabled in addition to all of the functionality described previously for sh. Typically, Job Control is enabled for the interactive shell only. Non-interactive shells typically do not benefit from the added functionality of Job Control. ๐ญ
With Job Control enabled, every command or pipeline the user enters at the terminal is called a job. All jobs exist in one of the following states: foreground, background, or stopped. These terms are defined as follows:
- A job in the foreground has read and write access to the controlling terminal. ๐
- A job in the background is denied read access and has conditional write access to the controlling terminal (see
stty(1)). - A stopped job is a job that has been placed in a suspended state, usually as a result of a
SIGTSTPsignal (seesignal.h(3HEAD)). ๐
Okay so every job that the shell starts gets a positive integer, called a job number, and the shell tracks it and uses it as an identifier to point at a specific job. Plus the shell keeps track of the current and previous jobs. The current job is the most recent job to be started or restarted. The previous job is the first non-current job. Slay. ๐
The acceptable syntax for a Job Identifier is literally:
%jobid
where jobid can be specified in any of the following formats:
%or+โ for the current job.โโ for the previous job.?<string>โ specify the job for which the command line uniquely contains string.nโ for job number n.prefโ where pref is a unique prefix of the command name. For example, if the commandls -l namewere running in the background, it could be referred to as%ls.prefcannot contain blanks unless it is quoted.
When Job Control is enabled, these commands get added to the user's environment to manipulate jobs:
bg [%jobid ...]โ resumes the execution of a stopped job in the background. If%jobidis omitted, the current job is assumed.fg [%jobid ...]โ resumes the execution of a stopped job in the foreground, and also moves an executing background job into the foreground. If%jobidis omitted, the current job is assumed.jobs [-p|-l] [%jobid ...]/jobs -x command [arguments]โ reports all jobs that are stopped or executing in the background. If%jobidis omitted, all jobs that are stopped or running in the background are reported. The following options modify/enhance the output ofjobs:-lโ report the process group ID and working directory of the jobs.-pโ report only the process group ID of the jobs.-xโ replace anyjobidfound incommandorargumentswith the corresponding process group ID, and then executecommandpassing itarguments.
kill [ -signal | -s signal ] %jobidโ builtin version ofkillto provide the functionality of thekillcommand for processes identified with ajobid.killpg [ -signal | -s signal ] %jobidโ builtin version ofkillpgto provide the functionality of thekillpgcommand for process groups identified with ajobid.pgrp [%jobid ...]โ print process group IDs for jobs.stop %jobid ...โ stops the execution of a background job(s).suspendโ stops the execution of the current shell (but not if it is the login shell).wait [%jobid ...]โ thewaitbuiltin accepts a job identifier. If%jobidis omitted,waitbehaves as described above under Special Commands.
โจ Command History Editing โจ
If compiled with -DINTERACTIVE, the Bourne Shell includes a command line history and a command line editor. Iconic behavior tbh. ๐
The behavior of the command line editor was defined with a prototype implementation in 1982 and has unique characteristics compared to other implementations. The basic editing functions have been inspired by the behavior of the editor ved(1). The command history editor in the Bourne Shell is using the same code that was introduced in 1984 with bsh(1). Legacy code but make it fashion. ๐
The history is implemented as a limited ring buffer. The most recently used command line is always moved from its previous position in the history list to the most recent entry. The size of the ring buffer is in HISTORY. If HISTORY is unset or set to 0, the current command line history is lost and command line editing is only supported on the current line, and this line is not kept in the history. Command line editing may be turned off completely by issuing the command set +o ved. The existing history is not affected by turning off the command line editor. No cap. ๐ซถ
Command lines from the existing history may be retrieved with the cursor keys (Cursor up and Cursor down). Typing CR or LF executes the command on the line with the cursor.
Each new command is appended to the end of the history. If the maximum size of the history is reached, the oldest command is removed. Identical commands are avoided as far as possible. If a command is entered that is already in the history, it is moved to the end of the history. Lowkey tidy. โจ
๐ History Editing Commands ๐
The following line editing commands are supported:
^Aโ move the cursor to the beginning of the current command line.^Cโ interrupt command line reading and parsing. The current command line is discarded and the next prompt is displayed. This helps to escape from the parser when it is in an unknown state. Main character rescue move. ๐ญ^Dโ erase the character under the cursor and then move the cursor to the next character.DELโ erase one character to the left of the cursor.^Eโ move the cursor to the end of the current command line.^Fโ move cursor one character to the right.^Hโ move cursor one character to the left.
Warning: on terminals that offer a large backspace key for deleting characters,^Hdoes not work directly as it is mapped toDEL. Use the Cursor left key instead in such a case. We love a keyboard plot twist. ๐
^Nโ move cursor to the next history line. See below for history navigation.^Pโ move cursor to the previous history line. See below for history navigation.^Uโ erase the whole line.^Vโ literal next, the next typed character is inserted into the command line without special meaning.^^โ get next character, convert it into a control character and insert it into the command line.CRโ finish current line and execute it.NLโ finish current line and execute it.TABโ do file name completion for the word to the left side of the cursor. If more than one file matches the current partial filename, aBEEPis generated. Typing a secondTABdisplays a list of matching names.ESC- ^Dโ erase the word to the right starting with the character under the cursor.ESC- DELโ erase the word to the left of the cursor.ESC- ^Fโ move cursor one word to the right.ESC- ^Hโ move cursor one word to the left.
The following commands are available to navigate within the history:
^Nโ move cursor to the next history line. When the cursor has been on the last line of the history, move the cursor to the first line of the history.^Pโ move cursor to the previous history line. When the cursor has been on the first line of the history, move the cursor to the last line of the history.ESC- ^Nโ search forwards in the history. The user is prompted for a search pattern. The previous search string is kept and may be edited. To enter a new search string, first type^U.ESC- ^Pโ search backwards in the history. The user is prompted for a search pattern. The previous search string is kept and may be edited. To enter a new search string, first type^U.ESC- pโ search backwards in the history. Clear the old search pattern first.ESC- nโ search forwards in the history. Clear the old search pattern first.ESC- CRโ return to the history line that was in use before the last search command.
Other characters are inserted into the command line text. Characters that are listed above as being edit command characters need to be quoted using the quote character ^^. If a line is entered via CR or NL, the current position of the cursor is irrelevant.
The command line editor remembers the cursor position for each command line in the history during the lifetime of the shell process. Obsessed with the continuity. ๐ฆ
โจ๏ธ History Editing Input Mappings โจ๏ธ
The command line history editor maps input from the terminal into mapped text before it is interpreted by the editor. If a match is found on the input from the terminal, the related input text is directly replaced by its replacement string. A mapping may be prevented by typing the map quote character, which is the nul character (^@), directly before the matching text is entered. If this text is usually interpreted by the history editor, you first need to type the history editing quoting character ^^. To be sure that you are able to literally enter some text, type ^^^@ (control up-arrow followed by Nul and the text). It's giving escape-room but make it keyboard. ๐
At startup (directly before the first shell command prompt is shown), the command line history editor first tries to initialize the terminal setup using the variables HOME, TERM, TERMCAP and TERMPATH.
If TERM is not set, the mapper establishes standard mappings for the cursor keys assuming an ANSI-compatible terminal.
If TERM is set, the mapper establishes mappings for the following termcap capabilities:
kuโ key cursor up, mapped to^P. The previous command line from the history is displayed.kdโ key cursor down, mapped to^N. The next command line from the history is displayed.krโ key cursor forward (right), mapped to^F. Move cursor one character to the right.klโ key cursor left, mapped to^H. Move cursor one character to the left.khโ key cursor -> Home, mapped to^A. The cursor is moved to the beginning of the current command line.@7โ key cursor -> End, mapped to^E. The cursor is moved to the end of the current command line.kDโ key Delete Character, mapped to\177(DEL). Erase one character to the left of the cursor.kbโ key Backspace, mapped to\177(DEL). Erase one character to the left of the cursor.
Note that the Backspace Key is the larger key that is just above the Carriage Return Key. In former times, this key was called Delete and sent the\177(DEL) character. Since companies followed the design of the IBM PC keyboard layout, the related key usually sends\010. If you like to literally enter a backspace into the command line, type^^^@^H(control up-arrow followed by Nul followed by^H). Keyboard lore fr fr. โจ๏ธ๐
After the mappings from the termcap entry for the current terminal type have been established, the shell tries to read the file $HOME/.bshmap to retrieve additional mappings.
Each line in the file $HOME/.bshmap has the following structure:
map_from:map_to:comment
map_fromis the string that is going to be replaced in the input.map_tois the string replacement.commentis optional comment that is not used for mapping itself.
If both map_from and map_to are empty, the related line is ignored by the mapper, so a line may contain:
::comment
okay bestie, still deep in map land, and there are some โจrulesโจ you literally cannot skip:
A nul character in either map_from or map_to is currently not supported, but an empty map_to is interpreted as a nul character.
If a line has an empty map_to and the comment field starts with a * like this:
map_from::*comment
then an existing mapping gets removed. Why do we care? Because it lets you dodge unwanted mappings that have been set up from the TERMCAP entry ๐ซถ. A typical use case for this feature is to avoid the mapping:
^H:^?:Key Backspace -> Delete Char
which is caused by the TERMCAP capability kb for terminals that create a backspace with the delete key. Annoying? yes. Fixable? also yes ๐
.
Since the file $HOME/.bshmap is read in a sequential way, a later line with the same map_from may establish a different mapping.
Length limits, because the shell is a little strict (valid):
- The maximum length of
map_fromis 16 bytes. - The maximum length of
map_tois 128 bytes. - The maximum total line length is 8192 bytes.
- Each entry takes exactly one line in the file.
Control characters may be written using the same escape sequences as permitted with TERMCAP.
The builtin map command may be used to enter additional maps at runtime. Iconic.
As the nul character is the quote character of the mapper, enter two nul characters to get one nul character in the edit input. And to enter a mapped string (such as cursor key output), first enter the quote character of the command line history editor control ^ (^^) octal 036, then enter a nul character and finally the otherwise mapped text. Yeah, it's giving secret handshake, but it works ๐ฅ.
๐ Termcap
The termcap data base is used to make the command history editor independent from the terminal capabilities. Cursor key output is retrieved from the data base and mapped to the cursor movement commands of the history editor. basically matchmaking, but for keycodes ๐.
The following variables are used by termcap:
HOMEโ To find the private files like$HOME/.termcap.TERMโ A name representing the type of the current terminal.TERMCAPโ This environment variable holds either a precompiled termcap entry or the pathname to be used to find a termcap database file. If it holds a precompiled entry that does not match theTERMenvironment, the termcap database is parsed as if theTERMCAPenvironment is not set. See section Parameter Substitution above for more information.TERMPATHโ IfTERMCAPis empty or not set, then theTERMPATHenvironment is scanned for pathnames of files that contain a termcap database. It holds a list of filenames separated by colons or spaces (i.e.,":"or" "). See section Parameter Substitution above for more information.
The following escape sequences are understood by the termcap implementation used by sh:
\\โ The literal character\.\Eโ The ESC character (ASCII 033).\eโ The ESC character (ASCII 033).\^โ The literal character^.\:โ The literal character:.\,โ The literal character,.\bโ The BACKSPACE character (ASCII 010).\fโ The FORMFEED character (ASCII 014).\lโ The LINEFEED character (ASCII 012).\nโ The NEWLINE character (ASCII 012).\rโ The CR character (ASCII 015).\sโ The SPACE character (ASCII 040).\tโ The TAB character (ASCII 007).\vโ The VERTICAL TAB character (ASCII 013).^cโ Maps to control(c) for any appropriate c.^?โ The DEL character (ASCII 0177).\nnnโ Maps to a character with the octal representation nnn with 1..3 octal digits.\0โ Maps to ASCII 0200.^@โ Maps to ASCII 00.
Mapping \0 to ASCII 0200 is required by the termcap documentation. A real nul character created from (^@) is currently neither supported by the upper layers of termcap, nor by the upper layers of the mapper. so close, yet so far ๐ญ.
๐๏ธ Large File Behavior
The Bourne Shell is large file aware. See largefile(7) for an extended description of the behavior of sh and jsh when encountering files greater than or equal to 2 Gbyte ( 2^31 bytes). big files, no fear ๐ช.
๐ช EXIT STATUS
Errors detected by the shell, such as syntax errors, cause the shell to return a non-zero exit status. If the shell is being used non-interactively, execution of the shell file is abandoned. Otherwise, the shell returns the exit status of the last command executed (see also the exit command above).
๐ jsh Only
If the shell is invoked as jsh and an attempt is made to exit the shell while there are stopped jobs, the shell issues one warning:
There are stopped jobs.
This is the only message. If another exit attempt is made, and there are still stopped jobs they are sent a SIGHUP signal from the kernel and the shell is exited. consider that your final warning bestie ๐.
๐ FILES
/etc/profileโ The system initialization file, executed for login shells./etc/sh.shrcโ The system wide startup file, executed for interactive shells.$HOME/.profileโ The personal initialization file, executed for login shells after/etc/profile.$HOME/.shrcโ The personal initialization file, executed after/etc/sh.shrc, for interactive shells whenENVis not set./etc/termcapโ The system wideTERMCAPfile.$HOME/.termcapโ The personalTERMCAPfile that by default is checked before/etc/termcap.$HOME/.bshmapโ A file with hand-crafted cursor mappings for the history editor.$HOME/.historyโ File with the saved the history after logout.$HOME/.globalsโ File with persistent global alias definitions..localsโ File with persistent directory local alias definitions./tmp/sh*โ Used as temporary files for here documents (<<redirection)./dev/nullโ NULL device used as stdin for non job-control background jobs./usr/lib/rshโ The location of the restricted Bourne Shell binary.
๐ท๏ธ ATTRIBUTES
See attributes(7) for descriptions of the following attributes:
/usr/bin/sh, /usr/bin/jsh
- Availability โ
SUNWcsu - CSI โ
Enabled
๐ SEE ALSO
Intro(1), bc(1), echo(1), getoptcvt(1), kill(1), bsh(1), ved(1), ksh(1), ksh93(1), login(1), newgrp(1), pfsh(1), pfexec(1), privileges(7), ps(1), pwd(1), set(1), sfind(1), shell_builtins(1), stty(1), test(1), umask(1), wait(1), waitid(2), rsh(8), su(8), swap(8), sysdef(8), termcap(1), ved(1), dup(2), exec(2), fork(2), pipe(2), ulimit(2), getrlimit(2), setrlimit(2), setlocale(3C), signal.h(3HEAD), passwd(5), profile(5), attributes(7), environ(7), largefile(7), XPG4(7)
(and yes, ved(1) is listed twice in the original โ we don't gatekeep, we just report the facts โจ)
โ ๏ธ WARNINGS
The use of setuid shell scripts is strongly discouraged.
like, seriously. don't. ๐ฉ
๐ NOTES
For compatibility with the Thompson shell, ^ is a synonym for | as pipeline separator. Do not use in new scripts. it's giving legacy, respectfully.
Words used for filenames in input/output redirection are not interpreted for filename generation (see File Name Generation section above). For example, cat file1 >a* creates a file named a*. no globbing there, bestie, it's literal.
The built-in command . file reads the whole file before any commands are executed. When a command substitution, a set of commands from eval, dosh, repeat, command, fc, jobs or trap are parsed, the whole set of command are read at once. alias and unalias commands in the file do not apply to any commands defined in the file or inside a set of commands executed with the named built-ins. sneaky, but that's the rule ๐
.
Because commands in pipelines are run as separate processes, variables set in a pipeline have no effect on the parent shell. what happens in the pipeline stays in the pipeline ๐ซถ.
If you get the error message 'cannot fork, too many processes', try using the wait(1) command to clean up your background processes. If this doesn't help, the system process table is probably full or you have too many active foreground processes. There is a limit to the number of process ids associated with your login, and to the number the system can keep track of.
Only the last process in a pipeline can be waited for. sorry to the rest of y'all ๐ญ.
If a command is executed, and a command with the same name is installed in a directory in the search path before the directory where the original command was found, the shell continues to exec the original command. Use the hash -r command to correct this situation. that's your refresh button ๐ฅ.
The Bourne shell has a limitation on the effective UID for a process. If this UID is less than 100 (and not equal to the real UID of the process), then the UID is reset to the real UID of the process.
If not in job control mode, the shell implements both foreground and background jobs in the same process group and they all receive the same signals, which can lead to unexpected behavior. It is, therefore, recommended to switch on job control mode via set -m in an interactive environment. pls do this, your future self will thank you ๐.
Parameter assignments that precede a special builtin command affect the shell itself. Parameter assignments that precede the call of a function are ignored.
When the shell executes a shell script that attempts to execute a non-existent command interpreter, the shell returns an erroneous diagnostic message that the shell script file does not exist. confusing? yeah. iconic? also yeah ๐.
If your platform does not provide an /etc/termcap file, or if your termcap database does not contain an entry for the terminal type you are using, the following command may be used to convert a terminfo entry into a termcap entry and to append it to your private termcap database
incofmp -C >> $HOME/.termcap
๐ COMPATIBILITY
This Bourne Shell started with the source state from OpenSolaris build 51 from October 2006. It was later changed to the equivalent state of build 144 from July 2010. The changes up to build 147 have not been applied because these later versions from Sun reduced the functionality. not me side-eyeing those later builds ๐.
Most changes fixed bugs or added functionality without changing the expected previous behavior. slay.
The following incompatible changes have been introduced in order to follow the POSIX standard. (yes, POSIX said so, we obey ๐)
number parameters
This version of the Bourne Shell is more picky when parsing numbers. Previous versions of the shell did accept e.g. 0x12 for the number 0 as parsing just stopped at the first non digit.
parameter assignment ๐
ok so listen โ this version of the Bourne Shell fixed the order of evaluation for parameter assignments so it goes left to right instead of right to left (which is how previous versions did it ๐). Translation: if one of your scripts is out here expecting that old non-standard behavior, it might just fail on you. vibe check your scripts, bestie.
parameter assignment preceding builtin commands ๐
with this version of the Bourne Shell, parameter assignment preceding builtin commands only affects the shell itself if this is related to a special builtin command. in previous versions? it affected the shell itself for any builtin command. so yeah, glow-up.
parameter import from the environment โจ
when the shell is in POSIX mode, it sets the export property on all shell variables imported from the environment. this makes all changes in these variables automatically visible to the next child process. the historic behavior was to pass the imported values to the child's environment but to use a separate storage location for the internal shell variable until the export builtin is explicitly called for a specific variable.
syntax errors in builtin commands ๐ญ
with this version of the Bourne Shell, only special builtin commands may terminate the whole shell in case that shell is not an interactive shell. in previous versions, all builtin commands could terminate a non-interactive shell if a utility syntax error or a fatal utility error was encountered.
the most prominent result of this change is that the builtin cd command no longer terminates a shell script in case that the cd command did not work for whatever reason. so be careful and always check the exit code in shell scripts. fr fr, check the exit code. ๐ซถ
expanding here documents ๐ฆ
with this version of the Bourne Shell, the quoting state is reset before a here document is expanded and restored thereafter. this avoids that
var=you
echo "`cat <<EOF
Hi $var
EOF`"
prints Hi \y\o\u as done by the historical Bourne Shell, instead of the expected Hi you. iconic fix, no notes.
case ๐ธ
when in POSIX mode, sh no longer implements a fallback to a simple string compare, in case that an attempt to match the pattern similar to fnmatch(3) fails.
this makes it behave different than the Korn Shell reference implementation but the undocumented behavior kept from old Bourne Shell versions may cause unexpected matches, like a match to the string [0-9] even though a match to decimal digits only was intended. ๐ so if your pattern game is a little loose, it'll show.
cd ๐ง
POSIX introduced new options -L and -P and defaults to logical mode while the historic Bourne Shell did implement a physical mode that operates on normalized directory names.
in logical mode, the command argument ../* may refer to different files than calling cd .. followed by a command with the argument *. in logical and physical mode, the command argument * may refer to different files than calling cd somedir followed by a command with the argument ../*.
while the latter problem is caused by the existence of a symlink in the new path, the first problem is caused by the behavior of cd -L. this is why the Bourne Shell, when not in POSIX mode (set -o posix not set), did not change it's default behavior and assumes cd -P when neither -L nor -P have been specified.
continue โญ
with SVr2 (1986), a parameter was introduced for continue. unfortunately, at the same time a bug was introduced and a big number did not continue the outermost loop, but rather did break the outermost loop. this shell fixes this bug. slay, honestly.
functions ๐
there is now a separate name space for functions and shell variables. this is not expected to cause problems. (key words: not expected ๐)
getopts ๐
POSIX requires getopts to set OPTARG to the failing option character in case that optstring starts with a :. previous versions of the shell did unset OPTARG in case of a failure. POSIX also requires the shell variable related to the name argument from getopts to be set to ? when getopts returns a non-zero exit code. previous versions of the shell did set name to the null string in this case.
kill ๐ฅ
the option parsing of the kill command was modified to be compatible to the POSIX standard. this is not expected to cause problems as the change only affects marginal cases with negative process id's that caused problems before as well. so like, it was already messy, we just cleaned it up a lil.
read ๐
the field splitting required by the POSIX standard does not skip multiple non-space field separators but rather assigns empty values to variables in such a case. this is a significant change in the behavior, but the historic behavior is not useful for non-space field separators as this would not allow e.g. reading the password file via read(1). honestly the old way was giving nothing, we're better off.
return ๐
in the original Bourne Shell, the return command only returns from inside a function. this version of the shell implements return also from inside a dot script as required by POSIX.
this change causes an incompatibility in case that a dot script is read from inside a function and the script is intended to return from the function. so likeโฆ mind the vibes on that one.
retval and Command Substitution ๐ซถ
this version of the shell no longer uses a command substitution as a checkpoint where the exitcode is remembered for $?. this affects calls to exit and return without parameter. if such a call did not happen after a regular command, but e.g. after a parameter assignment with a command substitution, the implicit return/exit code was the exit code of the last command substitution and now is the exit code of the last regular command.
pipes and words ๐ฆ
when in POSIX mode, the ^ character is not accepted as an alternate pipe | symbol. this results in different word delimiting rules, words that contain ^ do not need to be quoted.
set ๐
the output of the set command with no arguments was modified to include the quoting required by the POSIX standard. this is not expected to cause problems but the new output may be used as shell.
when in full POSIX mode (via set -o posix), functions are not listed amongst shell variables. this is expected to cause problems as POSIX does not include a method to list shell functions. ๐
calling set -- now causes the positional parameters to be unset. previous versions of the shell left the positional parameters untouched in this case. a portable method to clear the positional parameters is to call shift $#.
set -e and Command Substitution ๐ญ
the historic Bourne Shell did abort the first echo command in the following example:
sh -c '(set -e; echo ERR `false`; echo ERR); echo OK'
and printed only a single line with: OK.
POSIX requires to treat false as a sub shell, to let the main shell ignore the exit code from the command substitution and let it only use the exit code from the echo command. this requires to print:
ERR
ERR
OK
test ๐ฅ
the behavior of the builtin test utility was changed by POSIX. POSIX requires test to select it's behavior from the number of arguments in case that the number of arguments is in the range from 0..4. this results e.g. in test -r to return a zero exit code because -r is a non-empty string, while previous versions of the shell did return an error because -r is an unary operator that misses an argument. correctly written scripts do not suffer from this change. ๐
when not in POSIX mode (set -o posix not set), test still understands test -t without a parameter for compatibility with UNIX scripts.
times โฐ
the output of the times command was modified to be compatible to the POSIX standard. this is not expected to cause problems.
trap ๐
the output of the trap command was modified to be compatible to the POSIX standard. scripts that depend on the output of the trap command, when listing existing trap state, should be converted to be portable by checking whether the output starts with trap -- and then use a POSIX compliant parser.
the following other incompatible changes have been introduced:
pipes ๐
while in the original Bourne Shell none of the commands from a pipeline command was a child of the original shell, this version of the Bourne Shell tries to make all simple commands in a pipeline children from the original shell. in addition, if a builtin command is the rightmost command of a pipeline, it will now be run in the original shell. this permits commands like:
echo foo | read var
to set the variable var in the main shell. main character energy tbh.
I/O redirection on compound commands ๐
with the original Bourne Shell, I/O redirection on compound commands cause the compound commands to be run in a subshell and variable assignment inside such constructs not to affect the main shell. this version of the shell tries to avoid to run compound commands with I/O redirection in a subshell. variable assignment thus works as expected. ๐ซถ
if the input or the output of a while or until loop was redirected in the original Bourne Shell, the commands in the loop have been run in a sub-shell, and variables set or changed there had no effect on the parent process:
lastline=
while read line
do
lastline=$line
done < /etc/passwd
echo "lastline=$lastline" # lastline is empty!
in these cases, the input or output could be redirected by using exec, as in the following example:
# Save standard input (file descriptor 0) as file
# descriptor 3, and redirect standard input from the file
/etc/passwd:
exec 3<&0 # save standard input as fd 3
exec </etc/passwd # redirect input from file
lastline=
while read line
do
lastline=$line
done
...and then you wrap it up like this, bestie:
exec 0<&3 # restore standard input
exec 3<&- # close file descriptor 3
echo "$lastline" # lastline
This version of the shell works with both variants. ๐
timeโ okay so thetimetoken is now a reserved word. That permits timing pipelines as a whole, but it may cause problems when people assume that it is a command. When in doubt, calltime -pinstead, because the fact that the next word is an option disables thetimetoken from being recognized as a reserved word. ๐ฐ๏ธโจ
๐ BUGS ๐
None currently known. Iconic, honestly. ๐
Mail bugs and suggestions to schilytools@mlists.in-berlin.de or open a ticket at https://codeberg.org/schilytools/schilytools/issues. ๐ซถ
The mailing list archive may be found at:
https://mlists.in-berlin.de/mailman/listinfo/schilytools-mlists.in-berlin.de.
๐ AUTHORS ๐
The Bourne Shell was initially written by Stephen Richard Bourne at Bell Labs in 1976. The SVr4 release was written by various authors at AT&T in 1989. The Bourne Shell was later maintained by various people at AT&T and Sun Microsystems. Since 2006, the Bourne Shell has been maintained by Joerg Schilling and the schilytools project authors. ๐
The history editor has been added to the Bourne Shell in 2006. It was designed and implemented as a prototype in 1982 by Joerg Schilling on UNOS, the first UNIX clone. The current version of the history editor is compatible to ved(1). It was written in August 1984 by Joerg Schilling and P. Teuchert for the shell bsh(1) and has been maintained by Joerg Schilling since 1985. It is now maintained by the schilytools project authors. ๐งโจ
๐ SOURCE DOWNLOAD ๐
The source code for the Bourne Shell is included in the schilytools project and may be retrieved from the schilytools project at Codeberg at:
https://codeberg.org/schilytools/schilytools.
The download directory is:
https://codeberg.org/schilytools/schilytools/releases.
Thatโs the whole page, bestie โ source/version is Schily Bourne Shell, dated 2022/10/06, and the manual page is sh(1). Go forth and shell responsibly. ๐
๐๐ฆ
๐ฆ where this page comes from
- opensuse-leap 16.0: bosh 2022.10.16-160000.2.2 ยท CDDL-1.0
- opensuse-leap 16.0: bosh 2022.10.16-160000.2.2 ยท CDDL-1.0
- opensuse-leap 16.0: bosh 2022.10.16-160000.2.2 ยท CDDL-1.0
- opensuse-leap 16.0: bosh 2022.10.16-160000.2.2 ยท CDDL-1.0
- Copyright 2012-2021 J. Schilling
- Copyright 1989 AT&T
- Copyright (c) 2008, Sun Microsystems, Inc. All Rights Reserved
- Copyright (c) 1992, X/Open Company Limited All Rights Reserved
- Copyright (C) 2001-2004 by the
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms