POSH(1)

πŸ’… POSH(1) πŸ’… β€” User commands

okay bestie, we're doing this. this is the manual for posh(1), and it is long, so buckle up, hydrate, and let's go. 🫢


🌸 NAME 🌸

posh β€” Policy-compliant Ordinary SHell ✨


🌈 SYNOPSIS 🌈

posh [+-aCefilnuvx] [+-o option]
     [[-c command-string [command-name] | -s | file ] [argument...]]

πŸŽ€ DESCRIPTION πŸŽ€

So posh is a reimplementation of the Bourne shell β€” like, a command interpreter you can use both interactively and for scripts. it's giving classic, but make it policy-compliant. πŸ’–


✨ Shell Startup ✨

These next options? you can only put them on the command line, bestie. no sneaking them in elsewhere. 🚫

  • -c command-string β€” the shell executes the command(s) contained in command-string
  • -i β€” interactive mode β€” see below
  • -l β€” login shell β€” see below interactive mode β€” see below
  • -s β€” the shell reads commands from standard input; all non-option arguments are positional parameters

And on top of all those? the options described in the set builtin command can also be used on the command line. two for one, we love to see it. πŸ‘‘

If neither -c nor -s is specified, the first non-option argument specifies the name of a file the shell reads commands from. and if there are, like, no non-option arguments at all? the shell reads commands from standard input. simple. 🌸

Now β€” the name of the shell (i.e., the contents of the $0 parameter) gets determined like this:

  • if the -c option is used and there is a non-option argument, that argument is used as the name
  • if commands are being read from a file, the file is used as the name
  • otherwise, the name the shell was called with (i.e., argv[0]) is used

A shell is interactive if the -i option is used, or if both standard input and standard error are attached to a tty. An interactive shell has job control enabled (if available), ignores the INT, QUIT and TERM signals, and prints prompts before reading input (see the PS1 and PS2 parameters). πŸ’…

A shell is privileged if the -p option is used, or if the real user-id or group-id does not match the effective user-id or group-id (see getuid(2), getgid(2)). A privileged shell does not process $HOME/.profile β€” instead, the file /etc/suid_profile is processed. Clearing the privileged option causes the shell to set its effective user-id (group-id) to its real user-id (group-id). no cap. πŸ”₯

If the basename of the name the shell is called with (i.e., argv[0]) starts with -, or if the -l option is used, the shell is assumed to be a login shell, and it reads and executes the contents of /etc/profile and $HOME/.profile if they exist and are readable. πŸ¦‹

πŸ’€ Exit status tea: the exit status of the shell is 127 if the command file specified on the command line could not be opened, or non-zero if a fatal syntax error occurred during the execution of a script. In the absence of fatal errors, the exit status is that of the last command executed β€” or zero, if no command is executed.

🧚 Command Syntax 🧚

The shell begins parsing its input by breaking it into words. Words, which are sequences of characters, are delimited by unquoted white-space characters (space, tab and newline) or meta-characters (<, >, |, ;, &, ( and )). Aside from delimiting words, spaces and tabs are just ignored, while newlines usually delimit commands. 🌈

The meta-characters are used in building these tokens:

  • <, <&, <<, >, >&, >>, etc. are used to specify redirections (see Input/Output Redirection below)
  • | is used to create pipelines
  • ; is used to separate commands
  • & is used to create asynchronous pipelines
  • && and || are used to specify conditional execution
  • ;; is used in case statements
  • and lastly, ( ... ) are used to create subshells

White-space and meta-characters can be quoted individually using backslash (\), or in groups using double (") or single (') quotes. πŸ“Ž

And heads up β€” these characters are also treated specially by the shell, so they need quoting if they're supposed to represent themselves: \, ", ', #, $, `, ~, {, }, *, ? and [.

Let's break those down, because it's a lot:

  • the first three (\, ", ') are the quoting characters we just mentioned (see Quoting below)
  • #, if it's used at the beginning of a word, introduces a comment β€” everything after the # up to the nearest newline is ignored
  • $ introduces parameter, command and arithmetic substitutions (see Substitution below)
  • ` introduces an old-style command substitution (see Substitution below)
  • ~ begins a directory expansion (see Tilde Expansion below)
  • { and } delimit csh(1) style alternations (see Brace Expansion below)
  • and finally, *, ? and [ are used in file name generation (see File Name Patterns below)

As words and tokens are parsed, the shell builds commands, of which there are two basic types:

  1. simple-commands β€” typically programs that are executed
  2. compound-commands β€” like for and if statements, grouping constructs and function definitions

A simple-command consists of some combination of parameter assignments (see Parameters below), input/output redirections (see Input/Output Redirections below), and command words. The only restriction? parameter assignments have to come before any command words. πŸ“

The command words, if any, define the command that's to be executed and its arguments. The command may be a shell built-in command, a function, or an external command β€” i.e., a separate executable file that's located using the PATH parameter (see Command Execution below).

✨ Note that all command constructs have an exit status: for external commands, this is related to the status returned by wait(2) β€” if the command could not be found, the exit status is 127, and if it could not be executed, the exit status is 126. The exit status of other command constructs (built-in commands, functions, compound-commands, pipelines, lists, etc.) are all well defined and are described where the construct is described. The exit status of a command consisting only of parameter assignments is that of the last command substitution performed during the parameter assignment β€” or zero if there were no command substitutions.

Commands can be chained together using the | token to form pipelines, in which the standard output of each command but the last is piped (see pipe(2)) to the standard input of the following command. The exit status of a pipeline is that of its last command. πŸ”—

A pipeline may be prefixed by the ! reserved word, which causes the exit status of the pipeline to be logically complemented: if the original status was 0 the complemented status will be 1, and if the original status was not 0, then the complemented status will be 0. flipped. periodt. πŸ’…

Lists of commands can be created by separating pipelines by any of the following tokens: &&, ||, &, |& and ;.

The first two are for conditional execution:

  • cmd1 && cmd2 executes cmd2 only if the exit status of cmd1 is zero
  • || is the opposite β€” cmd2 is executed only if the exit status of cmd1 is non-zero

&& and || have equal precedence, which is higher than that of &, |& and ; β€” which also have equal precedence.

The & token causes the preceding command to be executed asynchronously, that is, the shell starts the command, but does not wait for it to complete (the shell does keep track of the status of asynchronous commands β€” see Job Control below). When an asynchronous command is started when job control is disabled (i.e., in most scripts), the command is started with signals INT and QUIT ignored and with input redirected from /dev/null (however, redirections specified in the asynchronous command have precedence). πŸŒ€

⚠️ Note that a command must follow the && and || operators, while a command need not follow &, |& and ;.

The exit status of a list is that of the last command executed β€” with the exception of asynchronous lists, for which the exit status is 0.

Compound commands are created using the following reserved words β€” and these words are only recognized if they're unquoted and if they're used as the first word of a command (i.e., they can't be preceded by parameter assignments or redirections):

case   else
do     esac   if       time    [[
done   fi     in       until   {
elif   for    select   while   }
🫢 Note: Some shells (but not this one) execute control structure commands in a subshell when one or more of their file descriptors are redirected, so any environment changes inside them may fail. To be portable, the exec statement should be used instead to redirect file descriptors before the control structure.

In the following compound command descriptions, command lists (denoted as list) that are followed by reserved words must end with a semi-colon, a newline, or a (syntactically correct) reserved word. For example, these are all valid:

{ echo foo; echo bar; }

{ echo foo; echo bar<newline>}

{ { echo foo; echo bar; } }

...but this one is not:

{ echo foo; echo bar }

πŸ¦‹ ( list )

Execute list in a subshell. There is no implicit way to pass environment changes from a subshell back to its parent. it's a whole separate little universe in there, bestie. πŸ™ˆ


🌸 { list }

Compound construct; list is executed, but not in a subshell. Note that { and } are reserved words, not meta-characters. πŸ‘‘


πŸŽ€ case word in [ [(] pattern [| pattern] ... ) list ;; ] ... esac

The case statement attempts to match word against the specified patterns; the list associated with the first successfully matched pattern is executed.

Patterns used in case statements are the same as those used for file name patterns, except that the restrictions regarding . and / are dropped. πŸ“Ž

Note that any unquoted space before and after a pattern is stripped; any space within a pattern must be quoted. Both the word and the patterns are subject to parameter, command, and arithmetic substitution as well as tilde substitution. ✨

For historical reasons, open and close braces may be used instead of in and esac (e.g., case $foo { *) echo bar; }). πŸ§“

The exit status of a case statement is that of the executed list; if no list is executed, the exit status is zero.


πŸ’– for name [ in word ... term ] do list done

where term is either a newline or a ;.

For each word in the specified word list, the parameter name is set to the word and list is executed. If in is not used to specify a word list, the positional parameters ("$1", "$2", etc.) are used instead. πŸ”

For historical reasons, open and close braces may be used instead of do and done (e.g., for i; { echo $i; }). πŸ§“

The exit status of a for statement is the last exit status of list; if list is never executed, the exit status is zero.


🌈 if list then list [elif list then list] ... [else list] fi

If the exit status of the first list is zero, the second list is executed; otherwise the list following the elif, if any, is executed with similar consequences. If all the lists following the if and elifs fail (i.e., exit with non-zero status), the list following the else is executed. πŸ“

The exit status of an if statement is that of the non-conditional list that is executed; if no non-conditional list is executed, the exit status is zero.

  • until list do list done β€” bestie this is the anti-while. πŸŒ™ Same shape as while, except the body only runs while the exit status of that first list is non-zero. It's the "keep going till it breaks" loop. Periodt.
  • while list do list done β€” a prechecked loop, meaning the vibe check happens before the body ever gets to run. The body executes as often as the exit status of the first list is zero. And the exit status of the whole while statement? It's the last exit status of the list in the loop body β€” but if the body never runs at all, the exit status is zero. πŸ’…
  • name () command β€” defines the function name. Peep the Functions section below for the full tea. And a note that matters: any redirections you write after a function definition are performed whenever the function is executed, not when the definition itself is executed. ikyk yk. πŸ”₯
  • time [ -p ] [ pipeline ] β€” the time reserved word, fully explained in the Command Execution section. ⏱️

✨ Quoting ✨

Quoting is literally just how you tell the shell "hey, don't be weird about these characters, take them at face value." 🫢 It stops the shell from treating characters or words as special. There are three methods:

  1. A backslash \ quotes the character right after it β€” unless that backslash sits at the end of a line, in which case both the \ and the newline get stripped. Bye. πŸ‘‹
  2. A single quote ' quotes everything up to the next single quote. (It can span multiple lines, no big deal. 🌸)
  3. A double quote " quotes all characters except $, ` and \, up to the next unquoted double quote. Inside double quotes, $ and ` keep their usual meaning (that's parameter, command or arithmetic substitution) β€” with the one exception that no field splitting is carried out on the results of double-quoted substitutions. πŸ’–

And for the \ inside a double-quoted string:

  • followed by \, $, ` or " β†’ it gets replaced by that second character
  • followed by a newline β†’ both the \ and the newline are stripped
  • followed by anything else β†’ both the \ and the character after it stay unchanged
Note: check out POSIX Mode below for a special rule about sequences of the form "......".....". Yeah, that's as cursed as it looks. πŸ’€

πŸŒ€ Substitution πŸŒ€

So the very first thing the shell does when executing a simple-command is perform substitutions on the words of the command. There are three kinds, and you already know them:

  • parameter substitution β†’ written $name or ${...}
  • command substitution β†’ written $(command) or `command`
  • arithmetic substitution β†’ written $((expression))

Parameter substitutions get their whole own section right below. πŸ‘‘

If a substitution shows up outside of double quotes, the results are generally subject to word or field splitting according to whatever IFS is currently set to. IFS is a list of characters used to break a string into several words. Any characters from the set space, tab and newline that appear in the IFS characters are called IFS white space. βœ‚οΈ

Sequences of one or more IFS white space characters, in combination with zero or one non-IFS white space characters, delimit a field. Special case, because of course there's a special case: leading and trailing IFS white space is stripped (so no leading or trailing empty field is created by it) β€” but leading or trailing non-IFS white space does create an empty field. πŸ™ƒ

Example time, bestie. If IFS is set to <space>:, then the sequence of characters <space>A<space>:<space><space>B::D contains four fields: A, B, ``, and D. Slay.

Also: if IFS is set to the null string, no field splitting is done at all. If it's unset, the default of space, tab and newline is used. ⭐

The results of substitution are, unless otherwise specified, also subject to brace expansion and file name expansion β€” those get their own sections below.

A command substitution gets replaced by the output generated by the specified command, which is run in a subshell. For $(command) substitutions, normal quoting rules apply when command is parsed. For the `command` form though? A \ followed by any of $, ` or \ is stripped (and a \ followed by any other character is unchanged).

And a very cute special case in command substitutions: a command of the form < file is interpreted to mean "substitute the contents of file". So $(< foo) has the same effect as $(cat foo) β€” but it's carried out more efficiently because no process is started. Efficiency queen. πŸ‘‘

NOTE: $(command) expressions are currently parsed by finding the matching parenthesis, regardless of quoting. This will hopefully be fixed soon. 🫠

Arithmetic substitutions get replaced by the value of the specified expression. For example, the command echo $((2+3*4)) prints 14. Math ate, fr fr. βž— See Arithmetic Expressions for a full description of an expression.


πŸŽ€ Parameters πŸŽ€

Parameters are shell variables β€” you can assign them values and access those values with a parameter substitution. A parameter name is either:

  • one of the special single punctuation or digit character parameters described below, or
  • a letter followed by zero or more letters or digits (_ counts as a letter πŸ’œ)

That second form can be treated as an array by appending an array index of the form [expr], where expr is an arithmetic expression. Array indices are currently limited to the range 0 through 1023, inclusive. Parameter substitutions take the form $name, ${name} or ${name[expr]}, where name is a parameter name.

If you substitute a parameter (or an array parameter element) that is not set, a null string is substituted β€” unless the nounset option is on (set -o nounset or set -u), in which case an error occurs. 🚨

So how do parameters get their values? Buckle up, there's a whole list:

  1. The shell implicitly sets some parameters like #, PWD, etc. β€” and this is the only way the special single character parameters get set.
  2. Parameters are imported from the shell's environment at startup. 🌱
  3. Parameters can be assigned on the command line. Like, FOO=bar sets the parameter FOO to bar. You can give multiple parameter assignments on a single command line, and they can be followed by a simple-command β€” in which case the assignments are in effect only for the duration of the command (and such assignments are also exported, see below for what that implies). Careful though: both the parameter name and the = must be unquoted for the shell to recognize it as a parameter assignment. πŸ’…
  4. Use the export and readonly commands β€” descriptions live in the Command Execution section.
  5. for and select loops set parameters, and so do the getopts, read and set -A commands.
  6. Last but not least, you can assign values using assignment operators inside arithmetic expressions (see Arithmetic Expressions below), or using the ${name=value} form of parameter substitution (see below). ✨

Parameters with the export attribute (set with the export command, or by parameter assignments followed by simple commands) get put in the environment (see environ(5)) of commands run by the shell, as name=value pairs. The order in which parameters appear in a command's environment is unspecified. And when the shell starts up, it extracts parameters and their values from its environment and automatically sets the export attribute on them.

Now the fun part β€” modifiers you can apply to the ${name} form of parameter substitution: 🧚

  • ${name:-word} β€” if name is set and not null, it gets substituted; otherwise word gets substituted.
  • ${name:+word} β€” if name is set and not null, word gets substituted; otherwise nothing gets substituted.
  • ${name:=word} β€” if name is set and not null, it gets substituted; otherwise name is assigned word and the resulting value of name is substituted.
  • ${name:?word} β€” if name is set and not null, it gets substituted; otherwise word is printed on standard error (preceded by name:) and an error occurs β€” normally causing termination of a shell script, function or .-script. 😭 If word is omitted, the string parameter null or not set is used instead.

In all the modifiers above, the : can be omitted β€” in which case the conditions only depend on name being set (as opposed to set and not null). And if word is needed, parameter, command, arithmetic and tilde substitution are performed on it; if word isn't needed, it's not evaluated. No wasted work, we love that. 🌸

These forms of parameter substitution also exist:

  • ${#name} β€” the number of positional parameters if name is *, @ or isn't specified at all; otherwise the length of the string value of parameter name.
  • ${#name[*]}, ${#name[@]} β€” the number of elements in the array name.
  • ${name#pattern}, ${name##pattern} β€” if pattern matches the beginning of the value of parameter name, the matched text is deleted from the result of the substitution. A single # gives the shortest match, two #'s gives the longest match.
  • ${name%pattern}, ${name%%pattern} β€” just like the ${..#..} substitution, but it deletes from the end of the value. 🎯

The special parameters πŸ‘‘

These are implicitly set by the shell and cannot be set directly using assignments:

  • ! β€” process id of the last background process started. If no background processes have been started, the parameter is not set.
  • # β€” the number of positional parameters (i.e., $1, $2, etc.).
  • $ β€” the process ID of the shell, or the PID of the original shell if it's a subshell.
  • - β€” the concatenation of the current single letter options (see the set command below for the list of options).
  • ? β€” the exit status of the last non-asynchronous command executed. If the last command was killed by a signal, $? is set to 128 plus the signal number.
  • 0 β€” the name the shell was invoked with (that is, argv[0]); or the command-name if it was invoked with the -c option and the command-name was supplied; or the file argument, if it was supplied. If the posix option is not set, $0 is the name of the current function or script.
  • 1 ... 9 β€” the first nine positional parameters that were supplied to the shell, function or .-script. Further positional parameters can be accessed using ${number}.
  • * β€” all positional parameters (except parameter 0), i.e., $1 $2 $3.... If used outside double quotes, the parameters are separate words (subjected to word splitting); if used within double quotes, the parameters are separated by the first character of the IFS parameter (or the empty string if IFS is null).
  • @ β€” same as $*, unless it's used inside double quotes β€” in which case a separate word is generated for each positional parameter, and if there are no positional parameters, no word is generated ("$@" can be used to access arguments, verbatim, without losing null arguments or splitting arguments with spaces). The GOAT. 🐐

The following parameters are set and/or used by the shell:

  • "CDPATH" β€” search path for the cd built-in command. Works the same way as PATH does, for those directories not beginning with / in cd commands. Note that if CDPATH is set and does not contain . nor an empty path, then the current directory is not searched. πŸ™ˆ
  • COLUMNS β€” This one's set to the number of columns on your terminal or window. Right now it's set to the cols value that stty(1) reports, as long as that value isn't zero. The interactive line editing modes use it, and so do the select, set -o and kill -l commands when they're formatting stuff into columns. πŸ’…
  • ERRNO β€” This would be an integer holding the shell's errno variable β€” it tells you why the last system call failed. But bestie, it's not implemented yet 😭.
  • EXECSHELL β€” If you set this, the shell assumes it contains the shell to use when executing commands that execve(2) fails to execute and that don't start with a `#! shell' sequence. (Yes, that's a backtick, hash, exclamation, two spaces, shell, and a single quote. Iconic.) ✨
  • FCEDIT β€” The editor used by the fc command (see below).
  • FPATH β€” Like PATH, but used when an undefined function is executed to locate the file defining the function. It's also searched when a command can't be found using PATH. See Functions below for more information.
  • HOME β€” The default directory for the cd command and the value substituted for an unqualified ~ (see Tilde Expansion below).
  • IFS β€” Internal field separator, used during substitution and by the read command, to split values into distinct arguments; normally set to space, tab and newline. See Substitution above for details.
Note: this parameter is not imported from the environment when the shell is started.
  • POSH_VERSION β€” The version of posh (readonly).
  • LINENO β€” The line number of the function or shell script that is currently being executed.
  • LINES β€” Set to the number of lines on the terminal or window. Not implemented yet.
  • OLDPWD β€” The previous working directory. Unset if cd has not successfully changed directories since the shell started, or if the shell doesn't know where it is.
  • OPTARG β€” When using getopts, it contains the argument for a parsed option, if it requires one.
  • OPTIND β€” The index of the last argument processed when using getopts. Assigning 1 to this parameter causes getopts to process arguments from the beginning the next time it is invoked.
  • PATH β€” A colon separated list of directories that are searched when looking for commands and .'d files. An empty string resulting from a leading or trailing colon, or two adjacent colons is treated as a ., the current directory.
  • PPID β€” The process ID of the shell's parent (readonly).
  • PS1 β€” The primary prompt for interactive shells. The prompt is printed verbatim (i.e., no substitutions are done). Default is β€˜$ ’ for non-root users, `# ' for root.. πŸ‘‘
  • PS2 β€” Secondary prompt string, by default `> ', used when more input is needed to complete a command.
  • PS4 β€” Used to prefix commands that are printed during execution tracing (see set -x command below). The prompt is printed verbatim (i.e., no substitutions are done). Default is `+ '.
  • PWD β€” The current working directory. Maybe unset or null if shell doesn't know where it is.
  • REPLY β€” Default parameter for the read command if no names are given. Also used in select loops to store the value that is read from standard input.
  • TMPDIR β€” The directory shell temporary files are created in. If this parameter is not set, or does not contain the absolute path of a writable directory, temporary files are created in /tmp.

🌸 Tilde Expansion 🌸

Tilde expansion, which happens in parallel with parameter substitution, is done on words starting with an unquoted ~. The characters following the tilde, up to the first /, if any, are assumed to be a login name. If the login name is empty, + or -, the value of the HOME, PWD, or OLDPWD parameter is substituted, respectively. Otherwise, the password file is searched for the login name, and the tilde expression is substituted with the user's home directory. If the login name is not found in the password file or if any quoting or parameter substitution occurs in the login name, no substitution is performed.

In parameter assignments (those preceding a simple-command or those occurring in the arguments of alias, export, and readonly), tilde expansion is done after any unquoted colon (:), and login names are also delimited by colons.

The home directory of previously expanded login names are cached and re-used. The alias -d command may be used to list, change and add to this cache (e.g., alias -d fac=/usr/local/facilities; cd ~fac/bin). πŸ¦‹


πŸ”₯ File Name Patterns πŸ”₯

A file name pattern is a word containing one or more unquoted ? or * characters or [..] sequences. Once brace expansion has been performed, the shell replaces file name patterns with the sorted names of all the files that match the pattern (if no files match, the word is left unchanged). The pattern elements have the following meaning:

  • ? β€” matches any single character.
  • * β€” matches any sequence of characters.
  • [..] β€” matches any of the characters inside the brackets. Ranges of characters can be specified by separating two characters by a -, e.g., [a0-9] matches the letter a or any digit. In order to represent itself, a - must either be quoted or the first or last character in the character list. Similarly, a ] must be quoted or the first character in the list if it is represent itself instead of the end of the list. Also, a ! appearing at the start of the list has special meaning (see below), so to represent itself it must be quoted or appear later in the list.
  • [!..] β€” like [..], except it matches any character not inside the brackets.
Note that posh currently never matches . and .., but the original ksh, Bourne sh and bash do, so this may have to change (too bad).

Note that none of the above pattern elements match either a period (.) at the start of a file name or a slash (/), even if they are explicitly used in a [..] sequence; also, the names . and .. are never matched, even by the pattern .*.

The POSIX character classes (i.e., [:class-name:] inside a [..] expression) are not yet implemented. 😭


πŸŽ€ Input/Output Redirection πŸŽ€

When a command is executed, its standard input, standard output and standard error (file descriptors 0, 1 and 2, respectively) are normally inherited from the shell. Three exceptions to this are commands in pipelines, for which standard input and/or standard output are those set up by the pipeline, asynchronous commands created when job control is disabled, for which standard input is initially set to be from /dev/null, and commands for which any of the following redirections have been specified:

  • > file β€” standard output is redirected to file. If file does not exist, it is created; if it does exist, is a regular file and the noclobber option is set, an error occurs, otherwise the file is truncated. Note that this means the command cmd < foo > foo will open foo for reading and then truncate it when it opens it for writing, before cmd gets a chance to actually read foo. πŸ’€
  • >| file β€” same as >, except the file is truncated, even if the noclobber option is set.
  • >> file β€” same as >, except the file an existing file is appended to instead of being truncated. Also, the file is opened in append mode, so writes always go to the end of the file (see open(2)).
  • < file β€” standard input is redirected from file, which is opened for reading.
  • <> file β€” same as <, except the file is opened for reading and writing.
  • << marker β€” after reading the command line containing this kind of redirection (called a here document), the shell copies lines from the command source into a temporary file until a line matching marker is read. When the command is executed, standard input is redirected from the temporary file. If marker contains no quoted characters, the contents of the temporary file are processed as if enclosed in double quotes each time the command is executed, so parameter, command and arithmetic substitutions are performed, along with backslash (\) escapes for $, `, \ and \newline. If multiple here documents are used on the same command line, they are saved in order.
  • <<- marker β€” same as <<, except leading tabs are stripped from lines in the here document.
  • <& fd β€” standard input is duplicated from file descriptor fd. fd can be a single digit, indicating the number of an existing file descriptor, the letter p, indicating the file descriptor associated with the output of the current co-process, or the character -, indicating standard input is to be closed.
  • >& fd β€” same as <&, except the operation is done on standard output.

In any of the above redirections, the file descriptor that is redirected (i.e., standard input or standard output) can be explicitly given by preceding the redirection with a single digit. Parameter, command and arithmetic substitutions, tilde substitutions and (if the shell is interactive) file name generation are all performed on the file, marker and fd arguments of redirections. Note however, that the results of any file name generation are only used if a single file is matched; if multiple files match, the word with the unexpanded file name generation characters is used.

For simple-commands, redirections may appear anywhere in the command, for compound-commands (if statements, etc.), any redirections must appear at the end. Redirections are processed after pipelines are created and in the order they are given, so

cat /foo/bar 2>&1 > /dev/null | cat -n will print an error with a line number prepended to it.


πŸ’… Arithmetic Expressions πŸ’…

Integer arithmetic expressions can be used inside $((..)) expressions, inside array references (e.g., name[expr]), as numeric arguments to the test command, and as the value of an assignment to an integer parameter.

Expression may contain alpha-numeric parameter identifiers, array references, and integer constants and may be combined with the following C operators (listed and grouped in increasing order of precedence).

Unary operators:

  • + - ! ~ ++ --

Binary operators:

  • ,
  • = *= /= %= += -= <<= >>= &= ^= |=
  • ||
  • &&
  • |
  • ^
  • &
  • == !=
  • < <= >= >
  • << >>
  • + -
  • * / %

Ternary operator:

  • ?: (precedence is immediately higher than assignment)

Grouping operators:

  • ( )

Integer constants may be specified with arbitrary bases using the notation base#number, where base is a decimal integer specifying the base, and number is a number in the specified base. 🌈

The operators get evaluated like this, bestie β€” read it slow, it's literally a whole vibe:

  • unary + β€” the result is just the argument (it's here for completeness, iconic of it honestly).
  • unary - β€” negation.
  • ! β€” logical not; the result is 1 if the argument is zero, 0 if it's not.
  • ~ β€” arithmetic (bit-wise) not.
  • ++ β€” increment; it has to be applied to a parameter (not a literal or any other expression) β€” the parameter gets incremented by 1. As a prefix operator, the result is the incremented value of the parameter; as a postfix operator, the result is the original value of the parameter.
  • ++ β€” similar to ++, except the parameter is decremented by 1. (Yes, that's what the page says, both of them. We don't ask questions, we just report. 🫑)
  • , β€” separates two arithmetic expressions; the left hand side is evaluated first, then the right. The result is the value of the expression on the right hand side.
  • = β€” assignment; the variable on the left is set to the value on the right.
  • *= /= %= += -= <<= >>= &= ^= |= β€” assignment operators; <var> <op>= <expr> is the same as <var> = <var> <op> ( <expr> ).
  • || β€” logical or; the result is 1 if either argument is non-zero, 0 if not. The right argument is evaluated only if the left argument is zero.
  • && β€” logical and; the result is 1 if both arguments are non-zero, 0 if not. The right argument is evaluated only if the left argument is non-zero.
  • | β€” arithmetic (bit-wise) or.
  • ^ β€” arithmetic (bit-wise) exclusive-or.
  • & β€” arithmetic (bit-wise) and.
  • == β€” equal; the result is 1 if both arguments are equal, 0 if not.
  • != β€” not equal; the result is 0 if both arguments are equal, 1 if not.
  • < β€” less than; the result is 1 if the left argument is less than the right, 0 if not.
  • <= >= > β€” less than or equal, greater than or equal, greater than. See <.
  • << >> β€” shift left (right); the result is the left argument with its bits shifted left (right) by the amount given in the right argument.
  • + - * / β€” addition, subtraction, multiplication, and division.
  • % β€” remainder; the result is the remainder of the division of the left argument by the right. The sign of the result is unspecified if either argument is negative.
  • <arg1> ? <arg2> : <arg3> β€” if <arg1> is non-zero, the result is <arg2>, otherwise <arg3>.

🧚 Functions 🧚

Functions get defined using the Bourne/POSIX shell name() syntax. They're like .-scripts in that they run in the current environment, but β€” plot twist β€” unlike .-scripts, shell arguments (i.e., positional parameters, $1, etc.) are never visible inside them. When the shell is figuring out where a command lives, functions get searched after special built-in commands, and before regular and non-regular built-ins, and before the PATH is searched.

Got a function you're over? Delete it with unset -f function-name. πŸ’…

Since functions run in the current shell environment, parameter assignments made inside functions are visible after the function completes. Main character energy, honestly.

The exit status of a function is that of the last command executed in the function. You can make a function finish immediately using the return command; that's also how you explicitly specify the exit status.


πŸŽ€ Command Execution πŸŽ€

After evaluation of command line arguments, redirections and parameter assignments, the type of command is determined: a special built-in, a function, a regular built-in, or the name of a file to execute found using the PATH parameter. The checks are made in the above order.

Special built-in commands differ from other commands in that the PATH parameter is not used to find them, an error during their execution can cause a non-interactive shell to exit, and parameter assignments specified before the command are kept after the command completes. And just to confuse things, if the posix option is turned off (see set command below), some special commands are very special in that no field splitting, file globbing, brace expansion nor tilde expansion is performed on arguments that look like assignments. Regular built-in commands are different only in that the PATH parameter is not used to find them.


πŸ‘‘ Job Control πŸ‘‘

Job control is the shell's ability to monitor and control jobs β€” which are processes or groups of processes created for commands or pipelines. At a minimum, the shell keeps track of the status of the background (i.e., asynchronous) jobs that currently exist; you can see all that using the jobs command. If job control is fully enabled (using set -m or set -o monitor), as it is for interactive shells, then:

  • the processes of a job are placed in their own process group,
  • foreground jobs can be stopped by typing the suspend character from the terminal (normally ^Z),
  • jobs can be restarted in either the foreground or background, using the fg and bg commands, respectively,
  • and the state of the terminal is saved or restored when a foreground job is stopped or restarted, respectively.
Note that only commands that create processes (e.g., asynchronous commands, subshell commands, and non-built-in, non-function commands) can be stopped; commands like read cannot be. 🫢

When a job is created, it is assigned a job-number. For interactive shells, this number is printed inside [..], followed by the process-ids of the processes in the job when an asynchronous command is run. A job may be referred to in bg, fg, jobs, kill and wait commands either by the process id of the last process in the command pipeline (as stored in the $! parameter) or by prefixing the job-number with a percent sign (%). Other percent sequences can also be used to refer to jobs:

  • %+ β€” the most recently stopped job, or, if there are no stopped jobs, the oldest running job.
  • %%, % β€” same as %+.
  • %- β€” the job that would be the %+ job, if the later did not exist.
  • %n β€” the job with job-number n.
  • %?string β€” the job containing the string string (an error occurs if multiple jobs are matched).
  • %string β€” the job starting with string string (an error occurs if multiple jobs are matched).

When a job changes state (e.g., a background job finishes or a foreground job is stopped), the shell prints the following status information:

[number] flag status command

where:

  • number β€” is the job-number of the job.
  • flag β€” is + or - if the job is the %+ or %- job, respectively, or a space if it is neither.
  • status β€” indicates the current state of the job and can be:
    • Running β€” the job has neither stopped nor exited (note that running does not necessarily mean consuming CPU time β€” the process could be blocked waiting for some event).
    • Done [(number)] β€” the job exited. number is the exit status of the job, which is omitted if the status is zero.
    • Stopped [(signal)] β€” the job was stopped by the indicated signal (if no signal is given, the job was stopped by SIGTSTP).
    • signal-description [(core dumped)] β€” the job was killed by a signal (e.g., Memory fault, Hangup, etc. β€” use kill -l for a list of signal descriptions). The (core dumped) message indicates the process created a core file.
  • command β€” is the command that created the process. If there are multiple processes in the job, then each process will have a line showing its command and possibly its status, if it is different from the status of the previous process.

Exit drama time: when an attempt is made to exit the shell while there are jobs in the stopped state, the shell warns the user that there are stopped jobs and does not exit. If another attempt is immediately made to exit the shell, the stopped jobs are sent a HUP signal and the shell exits. Similarly, if the nohup option is not set and there are running jobs when an attempt is made to exit a login shell, the shell warns the user and does not exit. If another attempt is immediately made to exit the shell, the running jobs are sent a HUP signal and the shell exits.


✨ BUILTIN UTILITIES ✨

posh implements the following builtin utilities, bestie β€” here's the whole roster:

  • .
  • :
  • [
  • break
  • builtin
  • continue
  • eval
  • exec
  • exit
  • false
  • return
  • set
  • shift
  • times
  • trap
  • wait
  • read
  • test
  • true
  • umask
  • unset
  • cd
  • command
  • echo
  • export
  • getopts
  • kill
  • local
  • pwd
  • readonly

🌸 FILES 🌸

~/.profile /etc/profile /etc/suid_profile

πŸ’€ BUGS πŸ’€

Any bugs in posh should be reported via the Debian BTS. Legitimate bugs are inconsistencies between manpage and behavior, and inconsistencies between behavior and Debian policy (currently SUSv3 compliance with the following exceptions: echo -n, binary -a and -o to test, local scoping).


⭐ VERSION ⭐

This page documents the Policy-compliant Ordinary SHell.


🫢 AUTHORS 🫢

This shell is based on pdksh.


🌈 SEE ALSO 🌈

awk(1), ksh(1), dash(1), ed(1), getconf(1), getopt(1), sed(1), stty(1), vi(1), dup(2), execve(2), getgid(2), getuid(2), open(2), pipe(2), wait(2), getopt(3), rand(3), signal(3), system(3), environ(5)


okay that's the whole page, we made it πŸŽ‰ this gem is filed under User commands, dated 01/24/2011, and it goes by POSH(1) β€” go forth and shell responsibly, bestie πŸ’–

πŸ“¦ where this page comes from