sh(1)
okay bestie, this is the sh(1) page from User Commands, and it's giving command programming language meets job control meets main character energy. let's get into it π
πΈ NAME πΈ
sh, obosh, jsh β the standard and job control shell and command interpreter. periodt.
β¨ SYNOPSIS β¨
/usr/bin/sh [βacefhikmnprstuvxP] [argument]...
/usr/bin/obosh [βacefhikmnprstuvxP] [argument]...
/usr/bin/jsh [βacefhikmnprstuvxP] [argument]...
π DESCRIPTION π
The /usr/bin/sh utility is a command programming language that executes commands read from a terminal or a file. literally the whole gig.
The name obosh permits one to call this implementation even when /usr/bin/sh has been linked to another shell. iykyk.
The jsh utility is an interface to the shell that provides all of the functionality of sh and enables job control (see Job Control section below). Job control may also be enabled by calling the shell via the standard name and then calling set -m.
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. Thereafter, 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 fromstring. The remaining arguments become positional parameters starting at$0.-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.
A pipeline is a sequence of one or more commands separated by |. The standard output of each command but the last is connected by a pipe(2) to the standard input of the next command. 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.
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.
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,nameis set to the next word taken from thein wordlist. Ifin word ...is omitted, then theforcommand executes thedolist once for each positional parameter that is set (see Parameter Substitution section below). Execution ends when there are no more words in the list.case word in [ pattern [ | pattern ] ) list ;; ] ... esacβ Acasecommand executes the list associated with the first pattern that matchesword. The form of the patterns is the same as that used for file-name generation (see File Name Generation section), except that a slash, a leading dot, or a dot immediately following a slash need not be matched explicitly.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.while list do list done/until 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.(list)β Executelistin a sub-shell.{ list;}βlistis executed in the current (that is, parent) shell. The{must be followed by a space.name () { list;}β Define a function which is referenced byname. 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 Execution section). The{and}are unnecessary if the body of the function is a command as defined above, under Commands.
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 { }
π¬ Comments Lines π¬
A word beginning with # causes that word and all the following characters up to a newline to be ignored. yes, queen, that's the comment moment.
π« Command Substitution π«
The shell reads commands from the string between two grave accents β you know, the backtick-looking things β 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 to remove backslashes (\) used to escape other characters.
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. 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.
If a backslash is used to escape a newline character (\newline), both the backslash and the newline are removed (see 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 is read, inserting a backslash to escape a dollar sign has no effect. Backslashes that precede characters other than \, grave accent, ", newline, and $ are left intact when the command string is read.
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`
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 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.
Any valid shell script can be used for command.
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.
π 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. that's the rule, bestie π«Ά
${parameter}β plugs in the value of parameter, if it even has one π«Ά. The braces are only mandatory when parameter is followed by a letter, digit, or underscore that isn't meant to be read as part of its name, or when the parameter name contains a dot (.). If parameter is*or@, every positional parameter gets substituted, starting at$1(separated by spaces). And$0gets set from argument zero when the shell is invoked β¨${parameter:βword}β Use Default Values. If parameter is unset or null, the expansion of word gets substituted instead; otherwise you just get the value of parameter. It's giving "bestie if you're not here i'm calling someone else" π${parameterβword}β Use Default Values. Same deal, except this only kicks in if parameter is unset β a null-but-set parameter gets a pass. If parameter is unset, the expansion of word is substituted; otherwise, the value of parameter.${parameter:=word}β Assign Default Values. If parameter is unset or null, the expansion of word is actually assigned to parameter. Either way, the final value of parameter is what gets substituted. Heads up: only variables can be assigned this way β not positional parameters, not special parameters, no exceptions β οΈ${parameter=word}β Assign Default Values. Same assignment energy, but again only if parameter is unset (null ones mind their business). If parameter is unset, the expansion of word is assigned to it. In all cases the final value of parameter is substituted. And again: only variables, not positional parameters or special parameters, can be assigned this way.${parameter:?word}β Indicate Error if Null or Unset π. If parameter is set and non-null, you get its value; otherwise the shell prints word and exits the shell. If word is omitted, the messageparameter null or not setis printed. This one is not playing around fr fr.${parameter?word}β Indicate Error if Null or Unset. If parameter is merely set (null counts!), substitute its value; otherwise print word and exit from the shell. If word is omitted, the messageparameter null or not setgets printed.${parameter:+word}β Use Alternative Value. If parameter is set and non-null, substitute word; otherwise substitute nothing at all (ghost town, empty string, silent treatment πΈ).${parameter+word}β Use Alternative Value. If parameter is set β just set β substitute word; otherwise substitute nothing.
ngl the colon is doing an unbelievable amount of heavy lifting here π if you take one thing from this page, take this next bit.
If the colon (:) is omitted from the above expressions, the shell only checks whether parameter is set or not. The following table summarizes the effect of the : π¦
β β β
β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
βββββββββββββββββββββ΄ββββββββββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββ
In all cases shown with "assign", parameter is assigned that value, which also replaces the expression π
And listen β in all of the above, word is not evaluated unless it's actually going to be used as the substituted string. So in this example, pwd only runs if d is unset or null. Efficiency slay:
echo ${d:β`pwd`}
πΈ the parameters the shell sets for you automatically, no notes πΈ
#β the number of positional parameters, in decimal.nβ the n-th positional parameter. The parameter name n lives in the range from1to$#.0β$0is set from argument zero when the shell is invoked. If you're running a script,$0is the name of the script π*β all positional parameters starting from$1."$*"expands to one argument containing all the positional parameters separated by a space.@β all positional parameters starting from$1."$@"expands to$#arguments. Yes, that's the whole difference. Yes, it matters enormously. iykyk π§ββ the flags supplied to the shell on invocation, or by thesetcommand.?β the decimal value returned by the last synchronously executed command. Only the low 8 bits of the exit code from the command are visible. And if the command was killed by a signal, the returned value is128+ the signal number π$β the decimal process number of this shell. Inside a subshell, this still expands to the same value as that of the current invoked shell. (iconic behaviour, honestly.)!β the process number of the last background command invoked.
π the parameters the shell uses β a.k.a. environment variables π
The following parameters are used by the shell. The parameters in this section are also referred to as environment variables.
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 the Execution section below). IfPATHis not set, it defaults to/usr/bin:.CDPATHβ the search path for thecdcommand.MAILβ if this parameter is set to the name of a mail file and theMAILPATHparameter is not set, the shell lets you know when mail arrives in the specified file π¬MAILCHECKβ how often (in seconds) the shell checks for the arrival of mail in the files specified by theMAILPATHorMAILparameters. 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 tells you when mail arrives 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.OPTARGβ used bygetoptsto store the argument if an option is using arguments.OPTINDβ used bygetoptsas the index of the next argument to be processed.PS1β primary prompt string, by default"$ "for normal users and"privileged users.(yes, that's literally how it reads β the quote never closes, i'm as confused as you π)PS2β secondary prompt string, by default"> ".REPLYβ set by theselectstatement and by thereadspecial builtin command when no arguments are supplied.IFSβ internal field separators, normally space, tab, and newline (see the Blank Interpretation section).SHACCTβ if this parameter is set to the name of a file writable by the user, the shell writes an accounting record in the file for each shell procedure executed π§ΎSHELLβ when the shell is invoked, it scans the environment (see the Environment section below) for this name. If the last pathname component equalsrshorrbosh, the shell is switched into a restricted shell.SYSV3β when theSYSV3Environment is set, the builtinechocommand is switched into SYSV3 mode and supports escape sequences and the BSD-noption to suppress the newline character at the end of the output.
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 PATH, PS1, PS2, MAILCHECK, OPTIND, and IFS. Default values for HOME and MAIL are set by login(1). And for security reasons, the value for IFS is never imported from the environment. periodt π
πΌ Blank Interpretation πΌ
After parameter and command substitution, the results of substitution get scanned for internal field separator characters (those found in IFS) and split into distinct arguments wherever those characters show up βοΈ
Explicit null arguments ("" or '') are retained. Implicit null arguments (the ones resulting from parameters that have no values) are removed. Rude, but consistent.
The IFS parameter is applied to any unquoted word. Thus.
IFS=X
echoXfoo
β¦executes the echo command with the argument foo.
π Input/Output Redirection π
okay so a command's input and output can be redirected with a special notation that the shell itself interprets. These little guys can appear anywhere in a simple-command, or they can precede or follow a command, and they are not passed on as arguments to the invoked command. Note: parameter and command substitution occurs before word or digit is used. β¨
<wordβ use filewordas standard input (file descriptor 0).>wordβ use filewordas standard output (file descriptor 1). If the file doesn't exist, it gets created. If the file does exist and thenoclobberoption is on, this causes an error π. Otherwise, it's truncated to zero length.>>wordβ use filewordas standard output. If the file exists, output is appended to it by first seeking to the EOF. Otherwise, the file is created.<>wordβ open filewordfor reading and writing as standard input.<<[-]wordβ after parameter and command substitution is done onword, the shell input is read up to the first line that literally matches the resultingword, or to an EOF. If, however, the hyphen (-) is appended to<<:- leading tabs are stripped from
wordbefore the shell input is read (but after parameter and command substitution is done onword); - leading tabs are stripped from the shell input as it is read and before each line is compared with
word; and - shell input is read up to the first line that literally matches the resulting
word, or to an EOF.
- leading tabs are stripped from
If any character of word is quoted (see the Quoting section later), no additional processing is done to the shell input. If no characters of word are quoted:
- parameter and command substitution occurs;
- (escaped)
\newlines are removed; and \must be used to quote the characters\,$, and`.
The resulting document becomes the standard input. π
<&digitβ use the file associated with file descriptordigitas standard input. Similarly for the standard output using>&digit.<&-β the standard input is closed. Similarly for the standard output using>&-.
If any of the above is preceded by a digit, the file descriptor that's associated with the file is the one specified by that digit (instead of the default 0 or 1). For example:
... 2>&1
associates file descriptor 2 with the file currently associated with file descriptor 1. π«Ά
The order in which redirections are specified is significant β the shell evaluates redirections left-to-right. For example:
... 1>xxx 2>&1
first associates file descriptor 1 with file xxx. Then it associates file descriptor 2 with the file associated with file descriptor 1 (that is, xxx). If the order of redirections were reversed, file descriptor 2 would be associated with the terminal (assuming file descriptor 1 had been) and file descriptor 1 would be associated with file xxx. π
Using the terminology 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. That is: 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 recursive slay π
If a command is followed by & and job control (see set -m) is not active, the default standard input for the 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 is scanned for the characters *, ?, and [. If one of these characters appears, the word is regarded as a pattern. The word is 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. The character . at the start of a file name or immediately following a /, as well as the character / itself, must be matched explicitly. no cap π₯
*β 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!, any character not enclosed is matched.
Notice that all quoted characters (see below) must be matched explicitly in a filename. β
πΈ Quoting πΈ
The following characters have a special meaning to the shell and cause termination of a word unless they're 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 are removed from the word before the command is executed. The pair \newline is removed from a word before command and parameter substitution. π
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. 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. π
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" ...). \ quotes the characters \, `, , (comma), and $. The pair \newline is 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. π
π Prompting π
When used interactively, the shell prompts with the value of PS1 before reading a command. 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. bestie's little nudge π«Ά
π Environment π
The environment (see environ(7)) is a list of name-value pairs that is 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. The environment seen by any executed command is thus 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 export commands. it's giving receipts π
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. If command is a Special Command, then
TERM=450 command
modifies the TERM variable in the current shell. main character energy, honestly π
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). β οΈ
β 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). If the command name does not match the name of a defined function, but matches one of the Special Commands listed below, it is executed in the shell process. π§
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).
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 is assumed to be a file containing shell commands. A sub-shell is spawned to read it. A parenthesized command is also executed in a sub-shell. π the lore is lore-ing
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). π¦
π§° Built-in Commands π§°
Okay so these ones? They get executed in the shell process itself β no new baby process, no forking, we stay in the shell. Input/output redirection is permitted for all of them, and file descriptor 1 is the default output location. And when Job Control is enabled, some extra Built-in Commands get added to the shell's environment (peep the Job Control section below for the deets π).
Commands marked with a + are treated specially, and it's giving very main character energy, because:
- 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.
Heads up bestie: in this version ofsh, parameter assignments that precede any builtin command affect the shell itself. Like, all of them. Not just the+girlies. π«Ά
+ :β no effect, literally does nothing. Returns a zero exit code. It's the "seen π " of commands.+ . filenameβ reads and executes commands from filename, then returns. The search path specified byPATHis used to find the directory containing filename.[ [expr] ]β see thetestbuiltin below.bg [%jobid ...]β when Job Control is enabled, thebgcommand is added to the user's environment to manipulate jobs. It resumes the execution of a stopped job in the background. If%jobidis omitted, the current job is assumed. (More deets in the Job Control section below π)+ break [ n ]β exits from the enclosingfororwhileloop, if any. Ifnis specified, it breaksnlevels. Bye at whatever depth you want bestie π¨cd [ argument ]β changes the current directory to argument. If arg is-the directory is changed to the previous directory. The shell parameterHOMEis the default argument. The shell parameterCDPATHdefines 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. If argument begins with a / the search path is not used. Otherwise, each directory in the path is searched for argument.
chdir [ dir ]βchdirchanges 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 theCDPATHvariable. If dir is the name of a shell variable whose value starts with a/, change to the directory named by that value.+ continue [ n ]β resumes the next iteration of the enclosingfororwhileloop. Ifnis specified, resume at the n-th enclosing loop. Round two, fight π₯echo [ arguments ... ]β the words in arguments are written to the shell's standard output, separated by space characters. Seeecho(1)for fuller usage and description.
If /usr/ucb appears before any other system directory in PATH and the first argument is -n, echo does not print a final new-line and does not interpret backslashed escape characters. Otherwise, -n is treated as a normal argument. If the $SYSV3 variable is set in the initial environment passed to the shell, the -n argument is also interpreted, but escape sequences are processed as usual.
The following character sequences are recognized within any of the arguments:
\aβ alert character.\bβ backspace.\cβ print line without new-line. All characters following the\cin the argument are ignored.\fβ form-feed.\nβ new-line.\rβ carriage return.\tβ tab.\vβ vertical tab.\\β backslash.\0nβ where n is the 8-bit character whose ASCII code is the 1-, 2- or 3-digit octal number representing that character.
+ eval [ argument ... ]β the arguments are read as input to the shell and the resulting command(s) executed. Yes queen, run it twice, eat the whole plate π½οΈ+ exec [-a name] [ argument ... ]β the command specified by the arguments is executed in place of this shell without creating a new process. Input/output arguments can appear and, if no other arguments are given, cause the shell input/output to be modified. The-aoption causes name rather than the first arg, to becomeargv[0]for the new process.+ exit [ n ]β causes the calling shell or shell script to exit with the exit status specified byn. Ifnis omitted the exit status is that of the last command executed (an EOF also causes the shell to exit.) Saying goodbye fr π+ export [ name ... ]β the given names are marked for automatic export to the environment of subsequently executed commands. If no arguments are given, variable names that have been marked for export during the current shell's execution are listed. (Variable names exported from a parent shell are listed only if they have been exported again during the current shell's execution.) Function names are not exported. Not the functions, bestie, keep those home π ββοΈfg [%jobid ...]β when Job Control is enabled, thefgcommand 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%jobidis omitted, the current job is assumed. (See the Job Control section below for more detail.)getopts optstring name [arg...]β use this in shell scripts to support command syntax standards (seeIntro(1)). This command parses positional parameters and checks for legal options. Seegetoptcvt(1)for usage and description.
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.
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.
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.
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. Rude but fair π
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.
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).
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. Iconic behaviour honestly β¨
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-roption 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. Memory queen behaviour π§jobs [-p|-l] [%jobid ...]andjobs -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. (See the Job Control section below for more detail.)kill [ -sig ] [ pid ] [ %job ] ...andkill -lβ sends either theTERM(terminate) signal or the specified signal to the specified jobs or processes. Signals are either given by number or by names (as given insignal.h(3HEAD)stripped of the prefixSIGwith the exception thatSIGCHDis namedCHLD). If the signal being sent isTERM(terminate) orHUP(hangup), then the job or process is sent aCONT(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 the 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. (Seekill(1).) Okay this one is a little scary, use responsibly bestie πlogin [ argument ... ]β equivalent toexec login argument....Seelogin(1)for usage and description.newgrp [ argument ]β equivalent toexec newgrp argument. Seenewgrp(1)for usage and description.pwdβ print the current working directory as absolute pathname that does not contain the filenames dot (.) or dot-dot (..). Seepwd(1)for usage and description. Clean paths only, no crumbs πΈread [ name ... ]β π
One line gets read from standard input, and using the internal field separator β that's IFS, normally space or tab β to figure out where words start and end, the first word goes to the first name, the second word to the second name, and so on, with all the leftover words dumped onto the last name π
. Lines can be continued with \newline.
Any character that isn't a newline can be quoted by putting a backslash in front of it. Those backslashes get removed before the words are handed out to the names, and no interpretation happens on whatever character follows the backslash. The exit code is 0, unless an EOF is encountered π.
readonly [ name ... ]β marks the given names as readonly, and the values of those names can't be changed by any assignment after that. No arguments? Then you get a list of every readonly name printed out, slay π.return [ n ]β makes a function exit with the return value you give in n. If you skip n, the return status is whatever the last command executed returned. Periodt.set [ -aefhkmntuvxP [ argument ... ] ]β thesetcommand is giving main character energy and supports these options:-aβ mark variables that get modified or created for export.-eβ exit immediately if a command exits with a non-zero exit status.-fβ disable file name generation.-hβ locate and remember function commands as the functions get defined (normally function commands are located when the function is executed).-kβ all keyword arguments get placed in the environment for a command, not just the ones that come before the command name.-mβ switch job control mode on. All jobs run in their own process groups. See section Job Control (jsh) below π.-nβ read commands but do not execute them. Setting-nin an interactive shell is ignored, because this could not be undone and the shell could not even be terminated anymore π.-tβ exit after reading and executing one command.-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 info. 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-.
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, no cap π«. The current set of flags can be found in $-. The remaining arguments are positional parameters and get assigned, in order, to $1, $2, ...
If no arguments are given, the names and values of all variables are printed π«Ά.
shift [ n ]β the positional parameters from$n+1 ...get renamed to$1 .... If n isn't given, it's assumed to be1.stop pid ...β halt execution of the process number pid. (seeps(1)).suspendβ stops the execution of the current shell (but not if it's the login shell, bestie π).test [expr]β evaluate conditional expressions. Seetest(1)for usage and description. If the value of the expression expr is true thentestreturns zero exit status; otherwise a non-zero exit status comes back.testreturns a non-zero exit status if there are no arguments.
These are the primaries used to evaluate a condition:
-b fileβ true if file exists and is a block special file.-c fileβ true if file exists and is a character special file.-d fileβ true if file exists and is a directory.-f fileβ true if file exists and is a regular file. Alternatively, if Bourne Shell users specify/usr/ucbbefore/usr/binin theirPATHenvironment variable, thentestreturns true if file exists and is (not-a-directory) π.-g fileβ true if file exists and its set group ID flag is set.-h fileβ true if file exists and is a symbolic link.-k fileβ true if file exists and has its set sticky bit set.-L fileβ true if file exists and is a symbolic link.-n stringβ true if the length of string is non-zero.-p fileβ true if file exists and is a named pipe (FIFO).-r fileβ true if file exists and is readable.-s fileβ true if file exists and has a size greater then zero.-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 the default value.-u fileβ true if file exists and its set user ID flag is set.-w fileβ true if file exists and is writable.-x fileβ 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 π.-z stringβ true if the length of string is zero.
And then the comparators, iykyk:
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.
All those primaries above can be combined with these operators, bestie:
( 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.
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 ... ]]β 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 get executed in order of signal number or 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. The trap command with no arguments prints a list of commands associated with each signal number π.
type [ name ... ]β for each name, indicate how it would be interpreted if used as a command name.typedisplays information about each operand identifying the operand as a shell built-in, shell intrinsic, function, hashed command, or keyword, and where applicable, may display the operand's path name. The meanings go like this:- shell built-in β a normal command built into the shell. Some of these commands don't need to be built into the shell. A command usually is in this group because it was built into the shell for historical reasons or because it's an extension to the current POSIX standard.
- special shell built-in β a command built into the shell that is subject to special treatment. This type of command needs to be built into the shell in order to be able to have the desired result.
- shell intrinsic β a command built into the shell. This type of command needs to be built into the shell in order to be able to have the desired result.
- function β a function defined in this shell.
- keyword β a keyword in the syntax of this shell.
- command β an external command identified by it's path name.
- hashed command β an external command that was already subject to a path name search and hashing.
ulimit [ [-HS] [-a | -McdefilLmnPqrRsStuv] ]ulimit [ [-HS] [resource-option] ] limit
ulimit prints or sets hard or soft resource limits. These limits are described in getrlimit(2) π.
If limit isn't 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).
okay so the -H option specifies a hard limit, and the -S option specifies a soft limit. If neither option is specified, ulimit sets both limits and prints 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.
-Mβ address space limit (in kbytes), usually-valias-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-lβ maximum size of locked memory (in kbytes)-Lβ maximum number of file locks-mβ maximum resident set size (in kbytes)-nβ maximum file descriptor plus 1-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)-Sβ maximum size of swap (in kbytes)-tβ maximum CPU time (in seconds)-uβ maximum number of child processes-vβ maximum size of virtual memory (in kbytes)
Not all resources are supported on all platforms. So yeah, vibe-check your platform before you get attached. π«Ά
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) too. π§
As an example of ulimit, to limit the size of a core file dump to 0 Megabytes, type the following:
ulimit -c 0
πΈ umask [ mask ] πΈ
The user file-creation mask is set to mask (see umask(1)).
If mask is omitted, the current value of the mask is printed. easy peasy. β¨
π + unset [ name ... ] π
For each name, remove the corresponding variable or function value. The variables PATH, PS1, PS2, MAILCHECK, and IFS cannot be unset. Readonly variables cannot be unset. no cap, they're staying. π
β wait [ n ] β
Wait for your background process whose process id is n and report its termination status. If n is omitted, all your shell's currently active background processes are waited for and the return code is zero. iconic waiting-room energy. π
π Job Control (jsh) π
When the shell is invoked as jsh 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)).
Every job that the shell starts is assigned a positive integer, called a job number which is tracked by the shell and is used as an identifier to indicate a specific job. Additionally, 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.
The acceptable syntax for a Job Identifier is of the form:
%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. pref cannot contain blanks unless it is quoted.
When Job Control is enabled, the following commands are added to the user's environment to manipulate jobs:
π bg [%jobid ...] π
Resumes the execution of a stopped job in the background. If %jobid is omitted the current job is assumed.
π fg [%jobid ...] π
Resumes the execution of a stopped job in the foreground, also moves an executing background job into the foreground. If %jobid is omitted the current job is assumed.
π jobs π
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 is reported. The following options modify/enhance the output of jobs:
-lβ Report the process group ID and working directory of the jobs.-pβ Report only the process group ID of the jobs.-xβ Replace any jobid found in command or arguments with the corresponding process group ID, and then execute command passing it arguments.
π kill [ -signal | -s signal ] %jobid π
Builtin version of kill to provide the functionality of the kill command for processes identified with a jobid.
π 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 ...] π
wait builtin accepts a job identifier. If %jobid is omitted wait behaves as described above under Special Commands.
π¦ 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).
π 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.
π FILES π
/etc/profileβ The system initialization file, executed for login shells.$HOME/.profileβ The personal initialization file, executed for login shells after/etc/profile./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 π§
- ATTRIBUTE TYPE: Availability β ATTRIBUTE VALUE:
SUNWcsu - ATTRIBUTE TYPE: CSI β ATTRIBUTE VALUE: Enabled
π₯ SEE ALSO π₯
Intro(1), bc(1), bosh(1), echo(1), getoptcvt(1), kill(1), bsh(1), ksh(1), ksh93(1), login(1), newgrp(1), pbosh(1), pfsh(1), pfexec(1), privileges(7), ps(1), pwd(1), set(1), shell_builtins(1), stty(1), test(1), umask(1), wait(1), waitid(2), rsh(8), su(8), swap(8), sysdef(8), 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)
β οΈ WARNINGS β οΈ
The use of setuid shell scripts is strongly discouraged. π¨
π NOTES π
Okay bestie, this is the fine-print era of the page, and it's giving "read me before you break something." Let's go. π«Ά
For compatibility with the Thompson shell, ^ is a synonym for | as a pipeline separator. Do not use in new scripts. Periodt.
Words used for filenames in input/output redirection are not interpreted for filename generation (see the File Name Generation section above). For example, cat file1 >a* creates a file named a*. No cap, that asterisk is literally just an asterisk here.
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. It's giving "read first, ask questions later." π
Because commands in pipelines are run as separate processes, variables set in a pipeline have no effect on the parent shell. Yep, the pipeline is its own little universe.
If the input or the output of a while or until loop is redirected, the commands in the loop are run in a sub-shell, and variables set or changed there have 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 can 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
exec 0<&3 # restore standard input
exec 3<&- # close file descriptor 3
echo "$lastline" # lastline
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. She's full, bestie. π
Only the last process in a pipeline can be waited for. That's just the rules.
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. Think of it as "the shell remembered the old address, and you need to make it re-check the map." πΊοΈ
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. Stay safe out there, interactive bestie. β¨
Parameter assignments that precede a special builtin command affect the shell itself. Parameter assignments that precede the call of a function are ignored. That's the rule, and she said what she said.
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. Yeah, the error message is lowkey misleading, but that's what happens. π
π BUGS π
None currently known. Iconic behavior, 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. Legends, all of them. π«‘
π¦ 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
Okay that's the whole page, bestie. This one's sh(1) from OpenSolaris Bourne Shell, dated 2022/10/06 β go forth and script 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-2018 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