SH(1POSIX)
๐ซง SH(1POSIX) โ bestie, it's the shell ๐
okay so quick heads up before we even start: this is SH(1POSIX), from the POSIX Programmer's Manual, section 1POSIX. โจ
๐ PROLOG
so like, this manual page is part of the POSIX Programmer's Manual. important disclaimer bestie: the Linux implementation of this interface may differ โ so go consult the corresponding Linux manual page for the deets on Linux behavior ๐ง โ or honestly the interface might just not be implemented on Linux at all. no cap. ๐
๐ธ NAME
sh โ shell, the standard command language interpreter ๐
๐ SYNOPSIS
sh [-abCefhimnuvx] [-o option]... [+abCefhimnuvx] [+o option]...
[command_file [argument...]]
sh -c [-abCefhimnuvx] [-o option]... [+abCefhimnuvx] [+o option]...
command_string [command_name [argument...]]
sh -s [-abCefhimnuvx] [-o option]... [+abCefhimnuvx] [+o option]...
[argument...]
๐ฆ DESCRIPTION
the sh utility is a command language interpreter, and it shall execute commands read from one of three places: a command line string, the standard input, or a specified file. pick your fighter ๐ฅ
the application shall ensure that the commands to be executed are expressed in the language described in Chapter 2, Shell Command Language. iykyk.
pathname expansion shall not fail due to the size of a file. periodt. ๐ซถ
shell input and output redirections have an implementation-defined offset maximum that is established in the open file description. like, that's just how it is.
โจ OPTIONS โจ
the sh utility shall conform to the Base Definitions volume of POSIX.1โ2017, Section 12.2, Utility Syntax Guidelines, with an extension for support of a leading <plus-sign> ('+') as noted below. iconic behavior honestly.
the -a, -b, -C, -e, -f, -m, -n, -o option, -u, -v, and -x options are described as part of the set utility in Section 2.14, Special Built-In Utilities. the option letters derived from the set special built-in shall also be accepted with a leading <plus-sign> ('+') instead of a leading <hyphen-minus> โ and that means the reverse case of the option as described in this volume of POSIX.1โ2017. flip it and reverse it ๐ซ
the following additional options shall be supported:
-cโ read commands from thecommand_stringoperand. set the value of special parameter0(see Section 2.5.2, Special Parameters) from the value of thecommand_nameoperand, and the positional parameters ($1,$2, and so on) in sequence from the remainingargumentoperands. no commands shall be read from the standard input. like, none. ๐ซ-iโ specify that the shell is interactive; see below. an implementation may treat specifying the-ioption as an error if the real user ID of the calling process does not equal the effective user ID, or if the real group ID does not equal the effective group ID. ๐-sโ read commands from the standard input.
if there are no operands and the -c option is not specified, the -s option shall be assumed. it's giving "default behavior, bestie." ๐
if the -i option is present, or if there are no operands and the shell's standard input and standard error are attached to a terminal, the shell is considered to be interactive. main character energy tbh.
๐ OPERANDS
the following operands shall be supported:
-โ a single<hyphen-minus>shall be treated as the first operand and then ignored. > โ ๏ธ if both'-'and"--"are given as arguments, or if other operands precede the single<hyphen-minus>, the results are undefined. no cap, don't do it.argumentโ the positional parameters ($1,$2, and so on) shall be set to arguments, if any.command_fileโ the pathname of a file containing commands. if the pathname contains one or more<slash>characters, the implementation attempts to read that file; the file need not be executable. if the pathname does not contain a<slash>character:- the implementation shall attempt to read that file from the current working directory; the file need not be executable.
- if the file is not in the current working directory, the implementation may perform a search for an executable file using the value of
PATH, as described in Section 2.9.1.1, Command Search and Execution.
special parameter 0 (see Section 2.5.2, Special Parameters) shall be set to the value of command_file. if sh is called using a synopsis form that omits command_file, special parameter 0 shall be set to the value of the first argument passed to sh from its parent (for example, argv[0] for a C program), which is normally a pathname used to execute the sh utility. ๐ง
command_nameโ a string assigned to special parameter0when executing the commands incommand_string. ifcommand_nameis not specified, special parameter0shall be set to the value of the first argument passed toshfrom its parent (for example,argv[0]for a C program), which is normally a pathname used to execute theshutility.command_stringโ a string that shall be interpreted by the shell as one or more commands, as if the string were the argument to thesystem()function defined in the System Interfaces volume of POSIX.1โ2017. if thecommand_stringoperand is an empty string,shshall exit with a zero exit status. cute and clean ๐ธ
๐ STDIN
the standard input shall be used only if one of the following is true:
- the
-soption is specified. - the
-coption is not specified and no operands are specified. - the script executes one or more commands that require input from standard input (such as a
readcommand that does not redirect its input).
see the INPUT FILES section.
when the shell is using standard input and it invokes a command that also uses standard input, the shell shall ensure that the standard input file pointer points directly after the command it has read when the command begins execution. it shall not read ahead in such a manner that:
- any characters intended to be read by the invoked command are consumed by the shell (whether interpreted by the shell or not), or
- characters that are not read by the invoked command are not seen by the shell.
when the command expecting to read standard input is started asynchronously by an interactive shell, it is unspecified whether characters are read by the command or interpreted by the shell. ๐คทโ๏ธ mystery vibe.
if the standard input to sh is a FIFO or terminal device and is set to non-blocking reads, then sh shall enable blocking reads on standard input. this shall remain in effect when the command completes. we love a setting that sticks around ๐ซถ
๐ INPUT FILES
the input file shall be a text file, except that line lengths shall be unlimited. go off, giant lines ๐
if the input file consists solely of zero or more blank lines and comments, sh shall exit with a zero exit status. iconic minimalism. โจ
๐ธ ENVIRONMENT VARIABLES ๐ธ
Okay so these are the little vibes-in-the-background that change how sh behaves. Set them, don't set them, whatever โ but here's what each one actually does, fr fr ๐
ENVโ This one hits only when an interactive shell is invoked, and only then. The shell runs parameter expansion on it (that's Section 2.6.2, Parameter Expansion, iykyk) and the resulting value gets used as a pathname of a file full of shell commands to execute in the current environment. The file does not need to be executable, bestie. But โ and this is important โ if the expanded value ofENVis not an absolute pathname, the results are unspecified. AlsoENVshall be ignored if the real and effective user IDs, or the real and effective group IDs, of the process are different. ๐FCEDITโ When the shell expands this one, it decides the default value for the-eeditor option's editor option-argument. IfFCEDITis null or unset,edshall be used as the editor. (yes,ed. the ancient one. iconic of her honestly)HISTFILEโ Determines a pathname naming a command history file. IfHISTFILEisn't set, the shell may try to access or create a file.sh_historyin the directory referred to by theHOMEenvironment variable. If the shell can't get both read and write access to, or create, the history file, it shall use an unspecified mechanism that lets the history operate properly. (And heads up โ every time this section says history "file", it means that unspecified mechanism in those cases.) An implementation may choose to access this variable only when initializing the history file; that initialization shall occur whenfcorshfirst try to retrieve entries from, or add entries to, the file โ as the result of commands issued by the user, the file named by theENVvariable, or implementation-defined system start-up files. Implementations may choose to disable the history list mechanism for users with appropriate privileges who don't setHISTFILE; the exact circumstances are implementation-defined. If more than one instance of the shell is using the same history file, it is unspecified how updates from those shells interact. As entries get deleted from the history file, they shall be deleted oldest first. It is unspecified when history file entries are physically removed from the history file. ๐HISTSIZEโ Determines a decimal number: the limit on how many previous commands are accessible. If this variable is unset, an unspecified default greater than or equal to 128 shall be used. The maximum number of commands in the history list is unspecified, but shall be at least 128. An implementation may choose to access this variable only when initializing the history file, as described underHISTFILE. So yeah โ it is unspecified whether changes you make toHISTSIZEafter the history file has been initialized actually do anything. ๐ซHOMEโ Determines the pathname of the user's home directory. The contents ofHOMEget used in tilde expansion, as described in Section 2.6.1, Tilde Expansion. ๐LANGโ Provides a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of POSIX.1-2017, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)LC_ALLโ If set to a non-empty string value, it overrides the values of all the other internationalization variables. Main character energy, honestly ๐LC_COLLATEโ Determines the behavior of range expressions, equivalence classes, and multi-character collating elements within pattern matching.LC_CTYPEโ Determines the locale for interpreting sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), which characters are defined as letters (character classalpha), and the behavior of character classes within pattern matching.LC_MESSAGESโ Determines the locale that should be used to affect the format and contents of diagnostic messages written to standard error.MAILโ Determines a pathname of the user's mailbox file, for the purposes of incoming mail notification. If this variable is set, the shell shall inform the user if the file named by the variable is created or if its modification time has changed. Informing the user shall be accomplished by writing a string of unspecified format to standard error, before writing the next primary prompt string. That check shall only happen after the interval defined by theMAILCHECKvariable has passed since the last such check. And the user shall only be informed ifMAILis set andMAILPATHis not set. ๐ฌMAILCHECKโ Establishes a decimal integer value specifying how often (in seconds) the shell shall check for mail arriving in the files specified by theMAILPATHorMAILvariables. The default value shall be 600 seconds. If set to zero, the shell shall check before issuing each primary prompt. โฐMAILPATHโ Provides a list of pathnames and optional messages, separated by<colon>characters. If this variable is set, the shell shall inform the user if any of the files named by the variable are created, or if any of their modification times change. (See the entry above forMAILfor the deets on mail arrival and user informing.) Each pathname can be followed by%and a string that shall be subjected to parameter expansion and written to standard error when the modification time changes. If a%character in the pathname is preceded by a<backslash>, it shall be treated as a literal%in the pathname. The default message is unspecified.
The MAILPATH environment variable takes precedence over the MAIL variable. ๐
NLSPATHโ Determines the location of message catalogs for the processing ofLC_MESSAGES.PATHโ Establishes a string formatted as described in the Base Definitions volume of POSIX.1-2017, Chapter 8, Environment Variables, used to effect command interpretation; see Section 2.9.1.1, Command Search and Execution. ๐ฃ๏ธPWDโ This variable shall represent an absolute pathname of the current working directory. Assignments to this variable may be ignored. ๐
โก ASYNCHRONOUS EVENTS โก
sh shall take the standard action for all signals (that's Section 1.4, Utility Description Defaults) โ with these exceptions, bestie:
If the shell is interactive, SIGINT signals received during command line editing shall be handled as described in the EXTENDED DESCRIPTION, and SIGINT signals received at other times shall be caught but no action performed.
If the shell is interactive:
SIGQUITandSIGTERMsignals shall be ignored.- If the
-moption is in effect,SIGTTIN,SIGTTOU, andSIGTSTPsignals shall be ignored. - If the
-moption is not in effect, it is unspecified whetherSIGTTIN,SIGTTOU, andSIGTSTPsignals are ignored, set to the default action, or caught. If they are caught, the shell shall, in the signal-catching function, set the signal to the default action and raise the signal (after taking any appropriate steps, such as restoring terminal settings).
The standard actions, and the actions described above for interactive shells, can be overridden by using the trap special built-in utility (see trap and Section 2.11, Signals and Error Handling).
๐จ๏ธ STDOUT ๐จ๏ธ
See the STDERR section. That's it. That's the whole thing. ๐
๐ญ STDERR ๐ญ
Except as otherwise stated (by the descriptions of any invoked utilities or in interactive mode), standard error shall be used only for diagnostic messages.
๐ OUTPUT FILES ๐
None. Zero. Nada. ๐ซ
๐ EXTENDED DESCRIPTION ๐
See Chapter 2, Shell Command Language. The functionality described in the rest of the EXTENDED DESCRIPTION section shall be provided on implementations that support the User Portability Utilities option (and the rest of this section is not further shaded for this option, k?).
๐ Command History List ๐
When the sh utility is being used interactively, it shall maintain a list of commands previously entered from the terminal in the file named by the HISTFILE environment variable. The type, size, and internal format of this file are unspecified. Multiple sh processes can share access to the file for a user, if file access permissions allow it; see the description of the HISTFILE environment variable. ๐ซถ
โ๏ธ Command Line Editing โ๏ธ
When sh is being used interactively from a terminal, the current command and the command history (see fc) can be edited using vi-mode command line editing. This mode uses commands, described below, similar to a subset of those described in the vi utility. Implementations may offer other command line editing modes corresponding to other editing utilities. ๐
The command set -o vi shall enable vi-mode editing and place sh into vi insert mode (see Command Line Editing (vi-mode)). This command also shall disable any other editing mode the implementation may provide. The command set +o vi disables vi-mode editing.
Certain block-mode terminals may be unable to support shell command line editing. If a terminal is unable to provide either edit mode, it need not be possible to set -o vi when using the shell on this terminal.
In the following sections, the characters erase, interrupt, kill, and end-of-file are those set by the stty utility. ๐
๐ง Command Line Editing (vi-mode) ๐ง
In vi editing mode, there shall be a distinguished line โ the edit line. All the editing operations which modify a line affect the edit line. The edit line is always the newest line in the command history buffer. โจ
With vi-mode enabled, sh can be switched between insert mode and command mode.
When in insert mode, an entered character shall be inserted into the command line, except as noted in vi Line Editing Insert Mode. Upon entering sh and after termination of the previous command, sh shall be in insert mode.
Okay so typing an escape character is literally your lil portal โ it shall switch sh into command mode (see vi Line Editing Command Mode ๐ซ). And once you're in command mode, every character you type shall either invoke a defined operation, be used as part of a multi-character operation, or be treated as an error. Bestie, a character that is not recognized as part of an editing command shall terminate any specific editing command and shall alert the terminal ๐ข. No cap.
And if sh receives a SIGINT signal in command mode (whether generated by typing the interrupt character or by other means ๐ญ), it shall terminate command line editing on the current command line, reissue the prompt on the next line of the terminal, and reset the command history (see fc) so that the most recently executed command is the previous command โ that is, the command that was being edited when it was interrupted is not re-entered into the history. The audacity of it, honestly ๐.
In the following sections, the phrase move the cursor to the beginning of the word'' shall mean move the cursor to the first character of the current word'' and the phrase move the cursor to the end of the word'' shall mean move the cursor to the last character of the current word''. And the phrase ``beginning of the command line'' indicates the point between the end of the prompt string issued by the shell (or the beginning of the terminal line, if there is no prompt string) and the first character of the command text. Slay, now you know where the vibe starts ๐.
๐ธ vi Line Editing Insert Mode ๐ธ
While in insert mode, any character typed shall be inserted in the current command line โ unless it is from the following set. Bestie, these are the special ones:
<newline>โ Execute the current command line. If the current command line is not empty, this line shall be entered into the command history (seefc). It's giving "commit and move on" โจeraseโ Delete the character previous to the current cursor position and move the current cursor position back one character. In insert mode, characters shall be erased from both the screen and the buffer when backspacing ๐งนinterruptโ Ifshreceives aSIGINTsignal in insert mode (whether generated by typing the interrupt character or by other means), it shall terminate command line editing with the same effects as described for interrupting command mode; see Command Line Editing (vi-mode) ๐คkillโ Clear all the characters from the input line. Poof, gone, iconic ๐<control>-Vโ Insert the next character input, even if the character is otherwise a special insert mode character. Sneaky lil bypass ๐<control>-Wโ Delete the characters from the one preceding the cursor to the preceding word boundary. The word boundary in this case is the closer to the cursor of either the beginning of the line or a character that is in neither theblanknorpunctcharacter classification of the current locale.end-of-fileโ Interpreted as the end of input insh. This interpretation shall occur only at the beginning of an input line. Ifend-of-fileis entered other than at the beginning of the line, the results are unspecified.<ESC>โ Placeshinto command mode. The glow-up moment ๐
Fr fr on that end-of-file one: only at the beginning of an input line, otherwise it's unspecified territory. Do not test it. Respect the boundary.
๐ vi Line Editing Command Mode ๐
In command mode for the command line editing feature, decimal digits not beginning with 0 that precede a command letter shall be remembered ๐. Some commands use these decimal digits as a count number that affects the operation.
The term motion command represents one of the commands:
<space> 0 b F l W ^ $ ; E f T w | , B e h t
If the current line is not the edit line, any command that modifies the current line shall cause the content of the current line to replace the content of the edit line, and the current line shall become the edit line. This replacement cannot be undone (see the u and U commands below ๐ญ). The modification requested shall then be performed to the edit line. When the current line is the edit line, the modification shall be done directly to the edit line.
Any command that is preceded by count shall take a count (the numeric value of any preceding decimal digits). Unless otherwise noted, this count shall cause the specified operation to repeat by the number of times specified by the count. Also unless otherwise noted, a count that is out of range is considered an error condition and shall alert the terminal, but neither the cursor position, nor the command line, shall change. No chaos, no movement, just a lil beep.
The terms word and bigword are used as defined in the vi description. The term save buffer corresponds to the term unnamed buffer in vi.
The following commands shall be recognized in command mode:
<newline>โ Execute the current command line. If the current command line is not empty, this line shall be entered into the command history (seefc).<control>-Lโ Redraw the current command line. Position the cursor at the same location on the redrawn line. Refresh queen behavior โจ#โ Insert the character'#'at the beginning of the current command line and treat the resulting edit line as a comment. This line shall be entered into the command history; seefc.=โ Display the possible shell word expansions (see Section 2.6, Word Expansions) of the bigword at the current command line position.
Note: This does not modify the content of the current line, and therefore does not cause the current line to become the edit line.
These expansions shall be displayed on subsequent terminal lines. If the bigword contains none of the characters '?', '*', or '[', an <asterisk> ('*') shall be implicitly assumed at the end. If any directories are matched, these expansions shall have a '/' character appended. After the expansion, the line shall be redrawn, the cursor repositioned at the current cursor position, and sh shall be placed in command mode.
\โ Perform pathname expansion (see Section 2.6.6, Pathname Expansion) on the current bigword, up to the largest set of characters that can be matched uniquely. If the bigword contains none of the characters'?','*', or'[', an<asterisk>('*') shall be implicitly assumed at the end. This maximal expansion then shall replace the original bigword in the command line, and the cursor shall be placed after this expansion. If the resulting bigword completely and uniquely matches a directory, a'/'character shall be inserted directly after the bigword. If some other file is completely matched, a single<space>shall be inserted after the bigword. After this operation,shshall be placed in insert mode. Autocomplete but make it editorial ๐*โ Perform pathname expansion on the current bigword and insert all expansions into the command to replace the current bigword, with each expansion separated by a single<space>. If at the end of the line, the current cursor position shall be moved to the first column position following the expansions andshshall be placed in insert mode. Otherwise, the current cursor position shall be the last column position of the first character after the expansions andshshall be placed in insert mode. If the current bigword contains none of the characters'?','*', or'[', before the operation, an<asterisk>('*') shall be implicitly assumed at the end.@letterโ Insert the value of the alias named_letter. The symbol letter represents a single alphabetic character from the portable character set; implementations may support additional characters as an extension. If the alias_lettercontains other editing commands, these commands shall be performed as part of the insertion. If no alias_letteris enabled, this command shall have no effect.[count]~โ Convert, if the current character is a lowercase letter, to the equivalent uppercase letter and vice versa, as prescribed by the current locale. The current cursor position then shall be advanced by one character. If the cursor was positioned on the last character of the line, the case conversion shall occur, but the cursor shall not advance. If the'~'command is preceded by a count, that number of characters shall be converted, and the cursor shall be advanced to the character position after the last character converted. If the count is larger than the number of characters after the cursor, this shall not be considered an error; the cursor shall advance to the last character on the line.[count].โ Repeat the most recent non-motion command, even if it was executed on an earlier command line. If the previous command was preceded by a count, and no count is given on the'.'command, the count from the previous command shall be included as part of the repeated command. If the'.'command is preceded by a count, this shall override any count argument to the previous command. The count specified in the'.'command shall become the count for subsequent'.'commands issued without a count. Again and again and again ๐[number]vโ Invoke thevieditor to edit the current command line in a temporary file. When the editor exits, the commands in the temporary file shall be executed and placed in the command history. If a number is included, it specifies the command number in the command history to be edited, rather than the current command line.[count]lโ (ell)[count]<space>โ Move the current cursor position to the next character position. If the cursor was positioned on the last character of the line, the terminal shall be alerted and the cursor shall not be advanced. If the count is larger than the number of characters after the cursor, this shall not be considered an error; the cursor shall advance to the last character on the line.[count]hโ Move the current cursor position to the countth (default1) previous character position. If the cursor was positioned on the first character of the line, the terminal shall be alerted and the cursor shall not be moved. If the count is larger than the number of characters before the cursor, this shall not be considered an error; the cursor shall move to the first character on the line.[count]wโ skrrt to the start of the next word โจ. But bestie, if the cursor was already parked on the last character of the line, the terminal gets alerted and the cursor does not advance, periodt. And if count is bigger than the number of words left after the cursor? That's not an error, don't panic โ the cursor just goes to the last character on the line.[count]Wโ same energy aswbut for the next bigword ๐ . Cursor on the last character of the line? Terminal alerted, cursor stays put. Count bigger than the bigwords after the cursor? Not an error, the cursor advances to the last character on the line.[count]eโ hop to the end of the current word. Already at the end of a word? Then it's the end of the next word, slay. Cursor on the last character of the line โ terminal alerted, cursor does not advance. Count bigger than the words after the cursor? Not an error, cursor lands on the last character on the line.[count]Eโ the bigword version ofe๐ธ. Same rules: at the end of a bigword โ go to the end of the next bigword; cursor on the last character โ terminal alerted, no advance; count bigger than the bigwords after โ not an error, cursor goes to the last character on the line.[count]bโ back it up to the beginning of the current word. Already at the beginning of a word? Then it's the beginning of the previous word. If the cursor was on the first character of the line, the terminal is alerted and the cursor is not moved. Count bigger than the words preceding the cursor? Not an error โ the cursor returns to the first character on the line.[count]Bโ the bigword version ofb๐ฆ. At the beginning of a bigword โ go to the beginning of the previous bigword. Cursor on the first character of the line โ terminal alerted, cursor not moved. Count bigger than the bigwords before the cursor? Not an error, cursor returns to the first character on the line.^โ move the cursor to the first character on the input line that is not a<blank>๐$โ move to the last character position on the current command line.0โ (yes, Zero.) Move to the first character position on the current command line.[count]|โ move to the countth character position on the current command line. No number specified? Then it's the first position. The first character position is numbered 1. If count is bigger than the number of characters on the line, that's not an error โ the cursor just gets placed on the last character on the line.[count]fcโ move to the first occurrence of the charactercthat happens after the current cursor position. Cursor on the last character of the line โ terminal alerted, cursor not advanced. And ifcliterally does not occur in the line after the cursor position โ terminal alerted, cursor not moved, no cap.[count]Fcโ move to the first occurrence of the charactercthat happens before the current cursor position ๐. Cursor on the first character of the line โ terminal alerted, cursor not moved. Ifcdoesn't occur in the line before the cursor position โ terminal alerted, cursor not moved.[count]tcโ move to the character before the first occurrence ofcthat happens after the current cursor position โจ. Cursor on the last character of the line โ terminal alerted, cursor not advanced. Ifcdoesn't occur after the cursor position โ terminal alerted, cursor not moved.[count]Tcโ move to the character after the first occurrence ofcthat happens before the current cursor position ๐. Cursor on the first character of the line โ terminal alerted, cursor not moved. Ifcdoesn't occur before the cursor position โ terminal alerted, cursor not moved.[count];โ repeat the most recentf,F,t, orTcommand, bestie. Any number argument on that previous command gets ignored. The errors are exactly the ones described for the repeated command.[count],โ repeat the most recentf,F,t, orTcommand too, but this time reverse the direction of that command ๐ซ. Any number argument on that previous command is ignored, same as above.aโ enter insert mode after the current cursor position. Characters you type get inserted before the next character.Aโ enter insert mode after the end of the current command line.iโ enter insert mode at the current cursor position. Characters you type get inserted before the current character.Iโ enter insert mode at the beginning of the current command line.Rโ enter insert mode, replacing characters from the command line starting at the current cursor position ๐ฅ.[count]cmotionโ delete the characters between the current cursor position and the cursor position that the specified motion command would land on. Then insert mode, placed before the first character following any deleted characters. If count is specified, it gets applied to the motion command. But heads up โ a count is ignored for these motion commands:0^$c
If the motion command is the character c, the entire current command line gets cleared and insert mode is entered. If the motion command would move the cursor toward the beginning of the command line, the character under the current cursor position is not deleted. If the motion command would move the cursor toward the end of the command line, the character under the current cursor position is deleted. If count is bigger than the number of characters between the current cursor position and the end of the command line in the direction the motion would move, that's not an error โ all the remaining characters in that range get deleted and insert mode is entered. And if the motion command is invalid: terminal alerted, cursor not moved, no text deleted. ๐
Cโ delete from the current character to the end of the line, then enter insert mode at the new end-of-line.Sโ clear the entire edit line and enter insert mode ๐.[count]rcโ replace the current character with the characterc. With a number count, replace the current character and the following count-1 characters. After this command, the cursor sits on the last character that was changed. If count is bigger than the number of characters after the cursor, not an error โ all the remaining characters get changed, periodt.[count]_โ append a<space>after the current character position, then append the last bigword in the previous input line after that<space>๐ธ. Then enter insert mode after the last character just appended. With a number count, append the *count*th bigword in the previous line.[count]xโ delete the character at the current cursor position and drop the deleted characters into the save buffer ๐ซถ. If the cursor was on the last character of the line, the character gets deleted and the cursor moves to the previous character (which is the new last character). If count is bigger than the number of characters after the cursor, not an error โ all the characters from the cursor to the end of the line get deleted.[count]Xโ delete the character before the current cursor position and put the deleted characters in the save buffer. The character under the current cursor position does not change. If the cursor was on the first character of the line โ terminal alerted, and theXcommand has no effect. If the line contained a single character,Xhas no effect either. If the line contained no characters, the terminal is alerted and the cursor is not moved ๐ญ. If count is bigger than the number of characters before the cursor, not an error โ all the characters from before the cursor back to the beginning of the line get deleted.
[count]dmotionโ deletes everything between where the cursor is rn and wherever thatmotioncommand would land it ๐ . Acountjust runs the motioncounttimes. If the motion heads toward the beginning of the line, the character under the cursor stays put (not deleted, bestie). If the motion isd, the whole line gets cleared, periodt. And ifcountis bigger than the number of characters left between the cursor and the end the motion is heading toward? Not an error โ all the remaining characters in that range just get yeeted. Everything deleted goes into the save buffer ๐.Dโ deletes every character from the cursor to the end of the line. All of it goes in the save buffer โจ.[count]ymotionโ yanks (aka copies, no cap) the characters from the cursor over to wherever the motion command lands, straight into the save buffer ๐ซถ. Acountgets applied to the motion command. If the motion heads toward the beginning of the line, the character under the cursor is not part of the yanked set. If the motion isy, the entire line gets yanked into the save buffer. The cursor does not move. And ifcountis bigger than the characters left in that range? Again, not an error โ all the remaining ones get yanked ๐.Yโ yanks from the cursor to the end of the line into the save buffer. Current character position stays exactly where it is ๐.[count]pโ puts a copy of whatever's in the save buffer after the cursor. Cursor advances to the last character put. Acountsays how many copies get put ๐ธ.[count]Pโ puts a copy of the save buffer before the cursor. Cursor moves to the last character put. Acountsays how many copies get put ๐ฆ.uโ undoes the last command that changed the edit line. Note: it shall not undo the copy of any command line to the edit line ๐.Uโ undoes all changes made to the edit line. Same deal: it shall not undo the copy of any command line to the edit line ๐.[count]k[count]-โ sets the current command line to be thecountth previous command line in the shell command history. Nocount? Defaults to1. The cursor gets positioned on the first character of the new command. If akor-would retreat past the max number of commands in effect for this shell (which is affected by theHISTSIZEenvironment variable), the terminal gets alerted and the command does nothing ๐ญ.[count]j[count]+โ sets the current command line to be thecountth next command line in the shell command history. Nocount? Defaults to1. Cursor goes on the first character of the new command. If ajor+advances past the edit line, the current command line gets restored to the edit line and the terminal gets alerted ๐.[number]Gโ sets the current command line to be the oldest command line stored in the shell command history. With anumber, it sets the current command line to be that command line number in the history instead. If that command line number doesn't exist, terminal gets alerted and nothing changes โญ./pattern<newline>โ moves backwards through the command history, searching forpattern, starting from the previous command line. Patterns use the pattern matching notation from Section 2.13, Pattern Matching Notation, EXCEPT that'^'has special meaning when it's the first character ofpattern๐ . In that case the'^'is discarded and the characters after it are matched only at the beginning of a line. Commands in the command history are treated as strings, not filenames. Pattern not found? Current command line stays unchanged and the terminal gets alerted ๐ญ. Found in a previous line? Current command line becomes that line and the cursor gets set to the first character of the new command line ๐.
If pattern is empty, the last non-empty pattern given to / or ? gets used. If there is no previous non-empty pattern, the terminal gets alerted and the current command line stays exactly as it was.
?pattern<newline>โ moves forwards through the command history, searching forpattern, starting from the next command line. Patterns use the pattern matching notation from Section 2.13, Pattern Matching Notation, EXCEPT that'^'is special when it's the first character ofpatternโจ. Then the'^'is discarded and the characters after it match only at the beginning of a line. Commands in the history are strings, not filenames. Not found? Current command line unchanged, terminal alerted ๐. Found in a following line? Current command line becomes that line, cursor set to the first character of the new command line ๐ฆ.
If pattern is empty, the last non-empty pattern given to / or ? gets used. If there's no previous non-empty pattern, terminal gets alerted and the current command line stays put.
nโ repeats the most recent/or?command. If there's no previous/or?, terminal gets alerted and the current command line stays unchanged ๐.Nโ repeats the most recent/or?command, but flips the direction of the search ๐ฅ. If there's no previous/or?, terminal gets alerted and the current command line stays unchanged.
๐ EXIT STATUS ๐
These are the exit values that shall be returned, bestie:
0โ the script to be executed consisted solely of zero or more blank lines or comments, or both.1โ125โ a non-interactive shell detected an error other thancommand_filenot found or executable, including but not limited to syntax, redirection, or variable assignment errors.126โ a specifiedcommand_filecould not be executed due to an[ENOEXEC]error (see Section 2.9.1.1, Command Search and Execution, item 2).127โ a specifiedcommand_filecould not be found by a non-interactive shell.
Otherwise, the shell shall return the exit status of the last command it invoked or attempted to invoke (see also the exit utility in Section 2.14, Special Built-In Utilities).
๐ญ CONSEQUENCES OF ERRORS ๐ญ
See Section 2.8.1, Consequences of Shell Errors.
The following sections are informative.
๐ธ APPLICATION USAGE ๐ธ
Standard input and standard error are the files that determine whether a shell is interactive when -i is not specified. For example:
sh > file
and:
sh 2> file
create interactive and non-interactive shells, respectively ๐ซถ. Although both accept terminal input, the results of error conditions are different, as described in Section 2.8.1, Consequences of Shell Errors; in the second example a redirection error encountered by a special built-in utility aborts the shell ๐.
A conforming application must protect its first operand, if it starts with a <plus-sign>, by preceding it with the -- argument that denotes the end of the options ๐.
Applications should note that the standard PATH to the shell cannot be assumed to be either /bin/sh or /usr/bin/sh, and should be determined by interrogation of the PATH returned by getconf PATH, ensuring that the returned pathname is an absolute pathname and not a shell built-in โจ.
For example, to determine the location of the standard sh utility:
command -v sh
On some implementations this might return:
/usr/xpg4/bin/sh
Furthermore, on systems that support executable scripts (the "#!" construct), it is recommended that applications using executable scripts install them using getconf PATH to determine the shell pathname and update the "#!" script appropriately as it is being installed (for example, with sed) ๐. For example:
#
# Installation time script to install correct POSIX shell pathname
#
# Get list of paths to check
#
Sifs=$IFS
Sifs_set=${IFS+y}
IFS=:
set -- $(getconf PATH)
if [ "$Sifs_set" = y ]
then
IFS=$Sifs
else
unset IFS
fi
#
# Check each path for 'sh'
#
for i
do
if [ -x "${i}"/sh ]
then
Pshell=${i}/sh
fi
done
#
# This is the list of scripts to update. They should be of the
# form '${name}.source' and will be transformed to '${name}'.
# Each script should begin:
#
# #!INSTALLSHELLPATH
#
scripts="a b c"
#
# Transform each script
#
for i in ${scripts}
do
sed -e "s|INSTALLSHELLPATH|${Pshell}|" < ${i}.source > ${i}
done
๐ EXAMPLES ๐
- Execute a shell command from a string:
sh -c "cat myfile"
- Execute a shell script from a file in the current directory:
sh my_shell_cmds
๐ง RATIONALE ๐ง
okay so bestie, storytime: the sh utility and the set special built-in utility share a common set of options. periodt. ๐
The name IFS was originally an abbreviation of โInput Field Separatorsโ โ but ngl, that name is misleading, because the IFS characters are actually used as field terminators. One justification for ignoring the contents of IFS upon entry to the script, beyond security considerations, is to assist possible future shell compilers. Allowing IFS to be imported from the environment prevents many optimizations that might otherwise be performed via dataflow analysis of the script itself. iykyk โจ
The text in the STDIN section about non-blocking reads concerns an instance of sh that has been invoked โ probably by a C-language program โ with standard input that has been opened using the O_NONBLOCK flag; see open() in the System Interfaces volume of POSIX.1โ2017. If the shell did not reset this flag, it would immediately terminate because no input data would be available yet and that would be considered the same as end-of-file. literally no data = bye bye ๐
The options associated with a restricted shell (command name rsh and the -r option) were excluded because the standard developers considered that the implied level of security could not be achieved and they did not want to raise false expectations. no cap, they were not playing games.
On systems that support set-user-ID scripts, a historical trapdoor has been to link a script to the name -i. When it is called by a sequence such as:
sh -
or by:
#! usr/bin/sh -
the historical systems have assumed that no option letters follow. Thus, this volume of POSIX.1โ2017 allows the single <hyphen-minus> to mark the end of the options, in addition to the use of the regular "--" argument, because it was considered that the older practice was so pervasive. An alternative approach is taken by the KornShell, where real and effective user/group IDs must match for an interactive shell; this behavior is specifically allowed by this volume of POSIX.1โ2017.
Note: There are other problems with set-user-ID scripts that the two approaches described here do not resolve. โ ๏ธ bestie, be careful out here.
The initialization process for the history file can be dependent on the system start-up files, in that they may contain commands that effectively preempt the user's settings of HISTFILE and HISTSIZE. For example, function definition commands are recorded in the history file, unless the set -o nolog option is set. If the system administrator includes function definitions in some system start-up file called before the ENV file, the history file is initialized before the user gets a chance to influence its characteristics. In some historical shells, the history file is initialized just after the ENV file has been processed. Therefore, it is implementation-defined whether changes made to HISTFILE after the history file has been initialized are effective. messy but iconic ๐
The default messages for the various MAIL-related messages are unspecified because they vary across implementations. Typical messages are:
"you have mail\n"
or:
"you have new mail\n"
It is important that the descriptions of command line editing refer to the same shell as that in POSIX.1โ2008 so that interactive users can also be application programmers without having to deal with programmatic differences in their two environments. It is also essential that the utility name sh be specified because this explicit utility name is too firmly rooted in historical practice of application programs for it to change. fr fr, sh is forever.
Consideration was given to mandating a diagnostic message when attempting to set vi-mode on terminals that do not support command line editing. However, it is not historical practice for the shell to be cognizant of all terminal types and thus be able to detect inappropriate terminals in all cases. Implementations are encouraged to supply diagnostics in this case whenever possible, rather than leaving the user in a state where editing commands work incorrectly. do your best, kings ๐ซถ
In early proposals, the KornShell-derived emacs mode of command line editing was included, even though the emacs editor itself was not. The community of emacs proponents was adamant that the full emacs editor not be standardized because they were concerned that an attempt to standardize this very powerful environment would encourage vendors to ship strictly conforming versions lacking the extensibility required by the community. The author of the original emacs program also expressed his desire to omit the program. Furthermore, there were a number of historical systems that did not include emacs, or included it without supporting it, but there were very few that did not include and support vi. The shell emacs command line editing mode was finally omitted because it became apparent that the KornShell version and the editor being distributed with the GNU system had diverged in some respects. The author of emacs requested that the POSIX emacs mode either be deleted or have a significant number of unspecified conditions. Although the KornShell author agreed to consider changes to bring the shell into alignment, the standard developers decided to defer specification at that time. At the time, it was assumed that convergence on an acceptable definition would occur for a subsequent draft, but that has not happened, and there appears to be no impetus to do so. In any case, implementations are free to offer additional command line editing modes based on the exact models of editors their users are most comfortable with. the drama? immaculate. ๐
Early proposals had the following list entry in vi Line Editing Insert Mode:
\ If followed by the erase or kill character, that character shall
be inserted into the input line. Otherwise, the <backslash>
itself shall be inserted into the input line.
However, this is not actually a feature of sh command line editing insert mode, but one of some historical terminal line drivers. Some conforming implementations continue to do this when the stty iexten flag is set. lowkey a plot twist ๐
In interactive shells, SIGTERM is ignored so that kill 0 does not kill the shell, and SIGINT is caught so that wait is interruptible. If the shell does not ignore SIGTTIN, SIGTTOU, and SIGTSTP signals when it is interactive and the -m option is not in effect, these signals suspend the shell if it is not a session leader. If it is a session leader, the signals are discarded if they would stop the process, as required by the System Interfaces volume of POSIX.1โ2017, Section 2.4.3, Signal Actions for orphaned process groups. protect the shell at all costs ๐ก๏ธโจ
๐ฎ FUTURE DIRECTIONS ๐ฎ
None. literally none. no notes. ๐
๐ SEE ALSO ๐
- Section 2.9.1.1, Command Search and Execution
- Chapter 2, Shell Command Language
cd,echo,exit,fc,pwd,invalid,set,stty,test,trap,umask,vi- The Base Definitions volume of POSIX.1โ2017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines
- The System Interfaces volume of POSIX.1โ2017,
dup(),exec,exit(),fork(),open(),pipe(),signal(),system(),ulimit(),umask(),wait()
๐ COPYRIGHT ๐
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
and thatโs the whole vibe, bestie ๐ซถ this lil masterpiece comes from IEEE/The Open Group, 2017 edition, aka SH(1POSIX) โ go forth and shell responsibly ๐ โจ๐
๐ฆ where this page comes from
- debian bookworm: manpages-posix 2017a-2 ยท Other
- debian trixie: manpages-posix 2017a-2 ยท Other
- ubuntu jammy: manpages-posix 2017a-2 ยท Other
- ubuntu noble: manpages-posix 2017a-2 ยท Other
- ubuntu resolute: manpages-posix 2017a-2build1 ยท Other
- ubuntu stonking: manpages-posix 2017a-2.1 ยท Other
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms