KSH(1)
๐ KSH(1) โ General Commands Manual ๐
โจ NAME โจ
ksh, rksh โ public domain Korn shell. okay so this is the shell bestie, and yes, itโs iconic.
๐ธ SYNOPSIS ๐ธ
ksh [-+abCefhiklmnpruvXx] [-+o option]
[-c string | -s | file [argument ...]]
๐ฌ DESCRIPTION ๐ฌ
okay so ksh is a command interpreter intended for both interactive and shell script use. Its command language is a superset of the sh(1) shell language. No cap.
The options are as follows:
-c stringโkshwill execute the command(s) contained in string.-iโ Interactive shell. A shell is โinteractiveโ if this option is used or if both standard input and standard error are attached to atty(4). An interactive shell has job control enabled, ignores theSIGINT,SIGQUIT, andSIGTERMsignals, and prints prompts before reading input (see thePS1andPS2parameters). For non-interactive shells, thetrackalloption is on by default (see thesetcommand below).-lโ Login shell. If the basename the shell is called with (i.e.argv[0]) starts with โ-โ or if this option is used, the shell is assumed to be a login shell and the shell reads and executes the contents of/etc/profileand$HOME/.profileif they exist and are readable.-pโ Privileged shell. A shell is โprivilegedโ if this option is used or if the real user ID or group ID does not match the effective user ID or group ID (seegetuid(2)andgetgid(2)). A privileged shell does not process$HOME/.profilenor theENVparameter (see below). Instead, the file/etc/suid_profileis processed. Clearing the privileged option causes the shell to set its effective user ID (group ID) to its real user ID (group ID).-rโ Restricted shell. A shell is โrestrictedโ if this option is used; if the basename the shell was invoked with was โrkshโ; or if theSHELLparameter is set to โrkshโ. The following restrictions come into effect after the shell processes any profile andENVfiles:- The
cdcommand is disabled. - The
SHELL,ENV, andPATHparameters cannot be changed. - Command names can't be specified with absolute or relative paths.
- The
-poption of the built-in commandcommandcan't be used. - Redirections that create files can't be used (i.e.
>,>|,>>,<>).
- The
-sโ The shell reads commands from standard input; all non-option arguments are positional parameters.
In addition to the above, the options described in the set built-in command can also be used on the command line: both [-+abCefhkmnuvXx] and [-+o option] can be used for single letter or long options, respectively.
If neither the -c nor the -s option is specified, the first non-option argument specifies the name of a file the shell reads commands from. If there are no non-option arguments, the shell reads commands from the standard input. The name of the shell (i.e. the contents of $0) is determined as follows: if the -c option is used and there is a non-option argument, it is used as the name; if commands are being read from a file, the file is used as the name; otherwise, the basename the shell was called with (i.e. argv[0]) is used.
If the ENV parameter is set when an interactive shell starts (or, in the case of login shells, after any profiles are processed), its value is subjected to parameter, command, arithmetic, and tilde (โ~โ) substitution and the resulting file (if any) is read and executed. In order to have an interactive (as opposed to login) shell process a startup file, ENV may be set and exported (see below) in $HOME/.profile โ future interactive shell invocations will process any file pointed to by $ENV:
export ENV=$HOME/.kshrc
$HOME/.kshrc is then free to specify instructions for interactive shells. For example, the global configuration file may be sourced:
. /etc/ksh.kshrc
The above strategy may be employed to keep setup procedures for login shells in $HOME/.profile and setup procedures for interactive shells in $HOME/.kshrc. Of course, since login shells are also interactive, any commands placed in $HOME/.kshrc will be executed by login shells too.
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 whitespace characters (space, tab, and newline) or meta-characters (<, >, |, ;, (, ), and &). Aside from delimiting words, spaces and tabs are ignored, while newlines usually delimit commands. The meta-characters are used in building the following tokens: <, <&, <<, >, >&, >>, etc. are used to specify redirections (see โInput/output redirectionโ below); | is used to create pipelines; |& is used to create co-processes (see โCo-processesโ below); ; is used to separate commands; & is used to create asynchronous pipelines; && and || are used to specify conditional execution; ;; is used in case statements; (( .. )) is used in arithmetic expressions; and lastly, ( .. ) is used to create subshells.
Whitespace and meta-characters can be quoted individually using a backslash (\), or in groups using double (") or single (') quotes. The following characters are also treated specially by the shell and must be quoted if they are to represent themselves: \, ", ', #, $, `, ~, {, }, *, ?, and [. The first three of these are the above mentioned quoting characters (see โQuotingโ below); #, if used at the beginning of a word, introduces a comment โ everything after the # up to the nearest newline is ignored; $ is used to introduce 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: simple-commands, typically programs that are executed, and compound-commands, such as 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 is that parameter assignments come before any command words. The command words, if any, define the command that is 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 is located using the PATH parameter; see โCommand executionโ below).
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; 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 0 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, unless the pipefail option is set. 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; if the original status was not 0, the complemented status will be 0.
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 && and || operators are "left-associative". For example, both of these commands will print only "bar":
$ false && echo foo || echo bar
$ true || echo foo && echo bar
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 SIGINT and SIGQUIT ignored and with input redirected from /dev/null (however, redirections specified in the asynchronous command have precedence). The |& operator starts a co-process which is a special kind of asynchronous process (see โCo-processesโ below). A command must follow the && and || operators, while it need not follow &, |&, or ;. 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. These words are only recognized if they are unquoted and if they are used as the first word of a command (i.e. they can't be preceded by parameter assignments or redirections):
case esac in until (( }
do fi name while ))
done for select ! [[
elif function then ( ]]
else if time ) {
โ ๏ธ ok bestie, quick heads-up before we go: some shells (not this one, ok? not ksh, don't @ me) run control structure commands in a subshell the second you redirect one of their file descriptors โ which means any environment changes you make inside them might justโฆ not stick ๐ญ. To be portable, use the exec statement to redirect file descriptors before the control structure instead. fr fr.
Also, little grammar law for everything below ๐ in these compound command descriptions, any command list (we call it list) that's followed by a reserved word has to end with a semicolon, a newline, or a (syntactically correct) reserved word. Like, all of these are valid:
$ { echo foo; echo bar; }
$ { echo foo; echo bar<newline> }
$ { { echo foo; echo bar; } }
And this one? Not valid ๐:
$ { echo foo; echo bar }
(list)โ runs list in a subshell. And nope, there's no implicit way to pass environment changes from a subshell back up to its parent. It's giving "what happens in the subshell stays in the subshell" ๐{ list; }โ a compound construct: list gets executed, but not in a subshell ๐. Heads up tho โ{and}here are reserved words, not meta-characters. ikyk.case word in [[(] pattern [| pattern] ...) list ;; ] ... esacโ thecasestatement tries to match word against a pattern, and the list attached to the first pattern that matches successfully is the one that runs โจ. Patterns incasestatements are the same as file name patterns, except the restrictions about.and/are dropped. Note that any unquoted space before and after a pattern gets stripped โ so any space inside a pattern has to be quoted. Both the word and the patterns are subject to parameter, command, and arithmetic substitution, plus tilde substitution ๐ธ. The initial(is optional, and so is the terminating;;on the final list. For historical reasons you can use open and close braces instead ofinandesac, e.g.case $foo { *) echo bar; }. The exit status of acasestatement is that of the executed list; if no list is executed, the exit status is zero ๐for name [in [word ...]]; do list; doneโ for each word in the word list you gave, the parameter name is set to that word and list runs. If you don't useinto specify a word list, the positional parameters ($1,$2, etc.) get used instead ๐ฆ. For historical reasons, open and close braces may be used instead ofdoanddone, e.g.for i; { echo $i; }. The exit status of aforstatement is the last exit status of list. And if there are no items, list doesn't execute at all and 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 runs; otherwise, the list following theelif, if there is one, runs with similar consequences ๐. If all the lists following theifandelifs fail (i.e. exit with a non-zero status), the list following theelseruns. The exit status of anifstatement is that of the non-conditional list that gets executed; if no non-conditional list is executed, the exit status is zero ๐select name [in word ...]; do list; doneโ ok this one is a whole vibe, it's literally a built-in menu maker ๐. Theselectstatement gives you an automatic way to present the user with a menu and let them pick from it. An enumerated list of the specified word(s) is printed on standard error, followed by a prompt (PS3: normally#?). Then a number corresponding to one of the enumerated words is read from standard input, name is set to the selected word (or unset if the selection isn't valid),REPLYis set to what was read (leading/trailing space is stripped), and list runs ๐ฅ.
If a blank line is entered (i.e. zero or more IFS characters), the menu gets reprinted without executing list. When list completes, the enumerated list is printed if REPLY is NULL, then the prompt is printed, and so on โ it just keeps vibing ๐. This process continues until an end-of-file is read, an interrupt is received, or a break statement is executed inside the loop. If in word ... is omitted, the positional parameters are used (i.e. $1, $2, etc.) ๐ฆ. For historical reasons, open and close braces may be used instead of do and done, e.g. select i; { echo $i; }. The exit status of a select statement is zero if a break statement is used to exit the loop, and non-zero otherwise ๐
until list; do list; doneโ works just likewhile, except the body is executed only while the exit status of the first list is non-zero ๐while list; do list; doneโ awhileis a pre-checked loop ๐. Its body executes as often as the exit status of the first list is zero. The exit status of awhilestatement is the last exit status of the list in the body of the loop; if the body isn't executed, the exit status is zero โจfunction name { list; }โ defines the function name (peep "Functions" below ๐ธ). Note that redirections specified after a function definition are performed whenever the function is executed, not when the function definition is executed. important distinction bestie, don't sleep on itname() commandโ mostly the same asfunction(see "Functions" below ๐ซถ)time [-p] [pipeline]โ thetimereserved word is described in the "Command execution" section โฐ(( expression ))โ the arithmetic expression expression is evaluated; equivalent tolet expression(see "Arithmetic expressions" and theletcommand, below ๐งฎ)[[ expression ]]โ similar to thetestand[ ... ]commands (described later), with these exceptions ๐:- Field splitting and file name generation are not performed on arguments ๐ซ
- The
-a(AND) and-o(OR) operators are replaced with&&and||, respectively ๐ - Operators (e.g.
-f,=,!) must be unquoted - The second operand of the
=,==and!=expressions are patterns (e.g. the comparison[[ foobar = f*r ]]succeeds ๐) - The
<and>binary operators do not need to be quoted with the\character - The single argument form of
test, which tests if the argument has a non-zero length, is not valid here โ explicit operators must always be used, e.g. instead of[ str ]use[[ -n str ]]๐ - Parameter, command, and arithmetic substitutions are performed as expressions are evaluated, and lazy expression evaluation is used for the
&&and||operators ๐ฅ. This means that in the following statement,$(< foo)is evaluated if and only if the filefooexists and is readable:
$ [[ -r foo && $(< foo) = b*r ]]
โจ Quoting โจ
Quoting is how you stop the shell from treating characters or words as special ๐. There are three methods of quoting, bestie โ three! ๐
First, \ quotes the following character โ unless it's at the end of a line, in which case both the \ and the newline get stripped โ๏ธ.
Second, a single quote (') quotes everything up to the next single quote (and yes, this may span lines ๐).
Third, a double quote (") quotes all characters except $, ` and \, up to the next unquoted double quote ๐. $ and ` inside double quotes keep their usual meaning (i.e. parameter, command, or arithmetic substitution) โ except no field splitting is carried out on the results of double-quoted substitutions. And if a \ inside a double-quoted string is followed by \, $, `, or ", it's replaced by that second character ๐ฆ; if it's followed by a newline, both the \ and the newline are stripped; otherwise, both the \ and the character following it stay exactly as they are ๐.
๐ Aliases ๐
There are two types of aliases: normal command aliases and tracked aliases ๐ฏโโ๏ธ.
Command aliases are normally used as a shorthand for a long or often-used command ๐. The shell expands a command alias (i.e. substitutes the alias name for its value) when it reads the first word of a command. An expanded alias gets re-processed to check for more aliases ๐. If a command alias ends in a space or tab, the following word is also checked for alias expansion ๐. The alias expansion process stops when a word that isn't an alias is found, when a quoted word is found, or when an alias word that's currently being expanded is found. periodt ๐
The following command aliases are defined automatically by the shell:
autoload='typeset -fu'
functions='typeset -f'
hash='alias -t'
history='fc -l'
integer='typeset -i'
local='typeset'
login='exec login'
nohup='nohup '
r='fc -s'
stop='kill -STOP'
Tracked aliases let the shell remember where it found a particular command ๐ต๏ธโโ๏ธ. The first time the shell does a path search for a command marked as a tracked alias, it saves the full path of the command ๐พ. The next time that command is executed, the shell checks the saved path to see if it's still valid, and if it is, it avoids repeating the path search โก. Tracked aliases can be listed and created using alias -t. Note that changing the PATH parameter clears the saved paths for all tracked aliases ๐งน. If the trackall option is set (i.e. set -o trackall or set -h), the shell tracks all commands ๐. This option is set automatically for non-interactive shells. For interactive shells, only the following commands are automatically tracked: cat(1), cc(1), chmod(1), cp(1), date(1), ed(1), emacs, grep(1), ls(1), mail(1), make(1), mv(1), pr(1), rm(1), sed(1), sh(1), vi(1), and who(1) ๐.
๐ธ Substitution ๐ธ
The very first step the shell takes in executing a simple-command is to perform substitutions on the words of the command ๐ค. There are three kinds of substitution, bestie: parameter, command, and arithmetic โจ.
- Parameter substitutions โ described in detail in the next section โ take the form
$nameor${...}๐ - Command substitutions take the form
$(command)or`command` - Arithmetic substitutions take the form
$((expression))๐งฎ
three flavors, all iconic, no cap ๐
okay so real talk: if a substitution shows up outside of double quotes, the result is generally gonna get hit with word/field splitting based on whatever the current value of IFS is. ๐
IFS is basically the list of characters that tell the shell "hey, break this string into words here." And any characters from the set space, tab, and newline that show up in IFS are called "IFS whitespace" โ that's literally the official name, no cap.
Sequences of one or more IFS whitespace characters, in combination with zero or one non-IFS whitespace characters, delimit a field. And there's a special case that lowkey matters: leading and trailing IFS whitespace gets stripped (so no leading or trailing empty field is created by it), but leading non-IFS whitespace does create an empty field. ๐
Example time bestie โจ โ if IFS is set to <space>:, and VAR is set to <space>A<space>:<space><space>B::D, then the substitution for $VAR results in four fields: 'A', 'B', '' (an empty field), and 'D'. And note: if IFS is set to the NULL string, no field splitting is done at all; if the parameter is unset, the default value of space, tab, and newline is used. ๐
Also โ and this is the part people trip on โ field splitting applies only to the immediate result of the substitution. Using the same example, the substitution for $VAR:E results in the fields 'A', 'B', '', and 'D:E' โ not 'A', 'B', '', 'D', and 'E'. This behavior is POSIX compliant, but it's incompatible with some other shell implementations which do field splitting on the word that contained the substitution, or which use IFS as a general whitespace delimiter. so yeah. different vibes, different shells. ๐
The results of substitution are, unless otherwise specified, also subject to brace expansion and file name expansion (see the relevant sections below, bestie, they're coming).
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 are used when command is parsed; however, for the `command` form, a '\' followed by any of '$', '`', or '\' is stripped (a '\' followed by any other character is unchanged). And here's a cute special case: in command substitutions, a command of the form <file is interpreted to mean "substitute the contents of file." Note that $(< foo) has the same effect as $(cat foo), but it's carried out more efficiently because no process is started. iconic behavior honestly. โก
Arithmetic substitutions are replaced by the value of the specified expression. For example, the command echo $((2+3*4)) prints 14. See "Arithmetic expressions" for a description of an expression. ๐งฎ
โจ Parameters โจ
Parameters are shell variables; they can be assigned values and their values can be accessed using 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 โ slay). ๐ธ
The latter form can be treated as arrays by appending an array index of the form [expr] where expr is an arithmetic expression. Parameter substitutions take the form $name, ${name}, or ${name[expr]} where name is a parameter name. If expr is a literal '@' then the named array is expanded using the same quoting rules as '$@', while if expr is a literal '*' then the named array is expanded using the same quoting rules as '$*'. If substitution is performed on a parameter (or an array parameter element) that is not set, a null string is substituted unless the nounset option is set (set -o nounset or set -u), in which case an error occurs. ๐ญ so watch out for that one.
๐ how parameters get their values ๐
Parameters can be assigned values in a number of ways. Let's count 'em, bestie:
- The shell implicitly sets some parameters like
'#','PWD', and'$'โ this is the only way the special single character parameters are set. ๐ - Parameters are imported from the shell's environment at startup. ๐ฑ
- Parameters can be assigned values on the command line: for example,
FOO=barsets the parameter "FOO" to "bar". Multiple parameter assignments can be given 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 (such assignments are also exported; see below for the implications of this). โ ๏ธ Note that both the parameter name and the'='must be unquoted for the shell to recognize a parameter assignment. - The
export,readonly, andtypesetcommands โ see their descriptions in the "Command execution" section. ๐ ๏ธ forandselectloops set parameters, as well as thegetopts,read, andset -Acommands. ๐
And lastly, parameters can be assigned values using assignment operators inside arithmetic expressions (see "Arithmetic expressions" below) or using the ${name=value} form of the parameter substitution (see below). ๐ซถ
๐ the export attribute ๐
Parameters with the export attribute (set using the export or typeset -x commands, or by parameter assignments followed by simple commands) are put in the environment (see environ(7)) of commands run by the shell as name=value pairs. The order in which parameters appear in the environment of a command is unspecified โ don't come for me, that's just how it is. ๐
When the shell starts up, it extracts parameters and their values from its environment and automatically sets the export attribute for those parameters. cute, right? ๐
๐ฆ parameter substitution modifiers ๐ฆ
Modifiers can be applied to the ${name} form of parameter substitution:
${name:-word}โ if name is set and not NULL, it is substituted; otherwise, word is substituted. ๐ซถ${name:+word}โ if name is set and not NULL, word is substituted; otherwise, nothing is substituted. (the swerve of it all)${name:=word}โ if name is set and not NULL, it is substituted; otherwise, it is assigned word and the resulting value of name is substituted. โ๏ธ${name:?word}โ if name is set and not NULL, it is substituted; otherwise, word is printed on standard error (preceded byname:) and an error occurs (normally causing termination of a shell script, function, or script sourced using the'.'built-in command). If word is omitted, the string "parameter null or not set" is used instead. ๐ญ that's the vibe check failing.
In the above modifiers, the ':' can be omitted, in which case the conditions only depend on name being set (as opposed to set and not NULL). If word is needed, parameter, command, arithmetic, and tilde substitution are performed on it; if word is not needed, it is not evaluated. ๐
lazy in the best way.
๐ the other substitution forms ๐
The following forms of parameter substitution can also be used:
${#name}โ the number of positional parameters if name is'*','@', or not specified; 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 substitution. A single'#'results in the shortest match, and two of them result in the longest match. โ๏ธ${name%pattern},${name%%pattern}โ like${..#..}substitution, but it deletes from the end of the value. (end-of-string energy, honestly)
๐ the special parameters ๐
The following special parameters are implicitly set by the shell and cannot be set directly using assignments โ so don't even try it bestie:
!โ 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 ($1,$2, etc.).$โ the PID of the shell, or the PID of the original shell if it is a subshell.
Do NOT use this mechanism for generating temporary file names; see mktemp(1) instead. ๐จ fr fr, like, actually don't.
-โ the concatenation of the current single letter options (see thesetcommand below for a list of options). ๐ฉ?โ the exit status of the last non-asynchronous command executed. If the last command was killed by a signal,$?is set to128plus the signal number. ๐0โ the name of the shell, determined as follows: the first argument tokshif it was invoked with the-coption and arguments were given; otherwise the file argument, if it was supplied; or else the basename the shell was invoked with (i.e.argv[0]).$0is also set to the name of the current script or the name of the current function, if it was defined with thefunctionkeyword (i.e. a Korn shell style function). ๐ท๏ธ1 ... 9โ the first nine positional parameters that were supplied to the shell, function, or script sourced using the'.'built-in command. Further positional parameters may be accessed using${number}. ๐ข*โ all positional parameters (except parameter0), i.e.$1,$2,$3, ... If used outside of double quotes, parameters are separate words (which are subjected to word splitting); if used within double quotes, parameters are separated by the first character of theIFSparameter (or the empty string ifIFSis NULL). ๐@โ same as$*, unless it's used inside double quotes, in which case a separate word is generated for each positional parameter. 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. ๐ that's the icon, that's the moment.
๐ฑ parameters the shell sets and/or uses ๐ฑ
_(underscore) โ when an external command is executed by the shell, this parameter is set in the environment of the new process to the path of the executed command. In interactive use, this parameter is also set in the parent shell to the last word of the previous command. WhenMAILPATHmessages are evaluated, this parameter contains the name of the file that changed (see theMAILPATHparameter, below). ๐ฌCDPATHโ search path for thecdbuilt-in command. It works the same way asPATHfor those directories not beginning with'/'or'.'incdcommands. โ ๏ธ Note that ifCDPATHis set and does not contain'.'or an empty path, the current directory is not searched. Also, thecdbuilt-in command will display the resulting directory when a match is found in any search path other than the empty path. ๐บ๏ธCOLUMNSโ set to the number of columns on the terminal or window. Currently set to the "cols" value as reported bystty(1)if that value is non-zero. This parameter is used by the interactive line editing modes, and by theselect,set -o, andkill -lcommands to format information columns. ๐
EDITOR โ๏ธ
So if VISUAL isn't set, this is the parameter that decides your command-line editing mode for interactive shells. The way it actually works is spelled out down in the VISUAL entry (it's literally below, keep scrolling bestie).
Note: traditionally,EDITORwas used to name an (old-style) line editor, likeed(1), andVISUALwas for a (new-style) screen editor, likevi(1). Which is exactly why, ifVISUALis set, it overridesEDITOR. The hierarchy is real.
ENV ๐ง
If this parameter is found to be set after any profile files are executed, the expanded value gets used as a shell startup file. It typically holds your function and alias definitions (i.e. the personality of your shell). slay.
EXECSHELL ๐
If set, this parameter is assumed to contain the shell that's used to execute commands that execve(2) fails to execute and which don't start with a #!shell sequence. It's the fallback bestie.
FCEDIT ๐
The editor used by the fc command (see below). That's the whole gig.
FPATH ๐
Like PATH, but used when an undefined function is executed, to locate the file that defines the function. It also gets searched when a command can't be found using PATH. See โFunctionsโ below for more info โ iykyk.
HISTCONTROL ๐ฐ๏ธ
A colon separated list of history settings:
ignoredupsโ if present, lines identical to the previous history line will not be saved.ignorespaceโ if present, lines starting with a space will not be saved. (sneaky mode, iconic)
Unknown settings are just ignored. no notes.
HISTFILE ๐
The name of the file used to store command history. When you assign to it, history is loaded from the specified file. Also, several invocations of the shell running on the same machine will share history if their HISTFILE parameters all point to the same file. group chat but for commands ๐
Note: ifHISTFILEisn't set, no history file is used. This is different from the original Korn shell, which uses$HOME/.sh_history. ok so we changed the rules, don't come for me.
HISTSIZE ๐
The number of commands normally stored for history. The default is 500.
HOME ๐
The default directory for the cd command, and the value substituted for an unqualified ~ (see โTilde expansionโ below). home sweet home fr.
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 the details.
Note: this parameter is not imported from the environment when the shell is started. she's built different.
KSH_VERSION ๐
The version of the shell and the date the version was created (read-only). โจ
LINENO ๐ข
The line number of the function or shell script that's currently being executed.
LINES ๐
Set to the number of lines on the terminal or window.
MAIL ๐ฌ
If set, the user will be informed of the arrival of mail in the named file. This parameter is ignored if the MAILPATH parameter is set. (she's the understudy, basically.)
MAILCHECK โฐ
How often, in seconds, the shell will check for mail in the file(s) specified by MAIL or MAILPATH. If set to 0, the shell checks before each prompt. The default is 600 (10 minutes).
MAILPATH ๐ฎ
A list of files to be checked for mail. The list is colon separated, and each file may be followed by a ? and a message to be printed if new mail has arrived. Command, parameter, and arithmetic substitution is performed on the message and, during substitution, the parameter $_ contains the name of the file. The default message is you have mail in $_.
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. (she's lost. it happens.)
OPTARG ๐
When using getopts, it contains the argument for a parsed option, if it requires one.
OPTIND ๐
The index of the next argument to be processed when using getopts. Assigning 1 to this parameter causes getopts to process arguments from the beginning the next time it is invoked. reset button, love that for you.
PATH ๐ค๏ธ
A colon separated list of directories that are searched when looking for commands and files sourced using the . command (see below). An empty string resulting from a leading or trailing colon, or two adjacent colons, is treated as a . (the current directory). yep, the current dir sneaks in, that's canon.
POSIXLY_CORRECT ๐
If set, this parameter causes the posix option to be enabled. See โPOSIX modeโ below.
PPID ๐จโ๐ฉโ๐ง
The process ID of the shell's parent (read-only).
PS1 ๐
The primary prompt for interactive shells. Parameter, command, and arithmetic substitutions are performed, and the prompt string can be customised using backslash-escaped special characters.
Note that since the command-line editors try to figure out how long the prompt is (so they know how far it is to the edge of the screen), escape codes in the prompt tend to mess things up. You can tell the shell not to count certain sequences (such as escape codes) by using the\[...\]substitution (see below) or by prefixing your prompt with a non-printing character (such as control-A) followed by a carriage return and then delimiting the escape codes with this non-printing character. By the way, don't blame me for this hack; it's in the originalksh. ๐ญ
The default prompt is the first part of the hostname, followed by $ for non-root users, # for root.
The following backslash-escaped special characters can be used to customise the prompt:
\aโ Insert an ASCII bell character.\dโ The current date, in the format โDay Month Dateโ for example โWed Nov 03โ.\D{format}โ The current date, with format converted bystrftime(3). The braces must be specified.\eโ Insert an ASCII escape character.\hโ The hostname, minus domain name.\Hโ The full hostname, including domain name.\jโ Current number of jobs running (see โJob controlโ below).\lโ The controlling terminal.\nโ Insert a newline character.\rโ Insert a carriage return character.\sโ The name of the shell.\tโ The current time, in 24-hour HH:MM:SS format.\Tโ The current time, in 12-hour HH:MM:SS format.\@โ The current time, in 12-hour HH:MM:SS AM/PM format.\Aโ The current time, in 24-hour HH:MM format.\uโ The current user's username.\vโ The current version ofksh.\Vโ Like\v, but more verbose.\wโ The current working directory.$HOMEis abbreviated as~.\Wโ The basename of the current working directory.$HOMEis abbreviated as~.\!โ The current history number. An unescaped!will produce the current history number too, as per the POSIX specification. A literal!can be put in the prompt by placing!!inPS1.\#โ The current command number. This could be different to the current history number, ifHISTFILEcontains a history list from a previous session.\$โ The default prompt character i.e.#if the effective UID is0, otherwise$. Since the shell interprets$as a special character within double quotes, it is safer in this case to escape the backslash than to try quoting it.\nnnโ The octal character nnn.\\โ Insert a single backslash character.\[โ Normally the shell keeps track of the number of characters in the prompt. Use of this sequence turns off that count.\]โ Use of this sequence turns the count back on.
Note that the backslash itself may be interpreted by the shell. Hence, to set PS1 either escape the backslash itself, or use double quotes. The latter is more practical:
PS1="\u "
This is a more complex example, which does not rely on the above backslash-escaped sequences. It embeds the current working directory, in reverse video, in the prompt string:
x=$(print \\001)
PS1="$x$(print \\r)$x$(tput so)$x\$PWD$x$(tput se)$x> "
PS2 ๐ท
Secondary prompt string, by default > , used when more input is needed to complete a command.
PS3 ๐
Prompt used by the select statement when reading a menu selection. The default is #? .
PS4 ๐ฅ
Used to prefix commands that are printed during execution tracing (see the set -x command below). Parameter, command, and arithmetic substitutions are performed before it is printed. The default is + .
PWD ๐
The current working directory. May be unset or NULL if the shell doesn't know where it is. (again: lost. she's doing her best.)
RANDOM ๐ฒ
A random number generator. Every time RANDOM is referenced, it is assigned the next random number in the range 0-32767. By default, arc4random(3) is used to produce values. If the variable RANDOM is assigned a value, the value is used as the seed to srand_deterministic(3) and subsequent references of RANDOM produce a predictable sequence. so like... choose chaos or choose the same chaos every time. your call bestie ๐
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.
SECONDS โฑ๏ธ
The number of seconds since the shell started or, if the parameter has been assigned an integer value, the number of seconds since the assignment plus the value that was assigned. time is fake but the math is real โจ
TERMโ the terminal type bestie, like literally which terminal you're on. If it's set, it gets used to figure out the escape sequence for clearing the screen โจTMOUTโ set it to a positive integer in an interactive shell and it's giving timeout energy: it's the max number of seconds the shell waits for input after printing the primary prompt (PS1). Blow past that time and the shell just exits. ๐TMPDIRโ the directory where temporary shell files get created. If this parameter isn't set, or it doesn't contain the absolute path of a writable directory, temp files go in/tmp. Simple as that ๐ซถVISUALโ if set, this parameter controls the command-line editing mode for interactive shells. If the last component of the path in this parameter contains the stringvi,emacs, orgmacs, then thevi(1),emacs, orgmacs(Gosling emacs) editing mode is enabled, respectively. Also peep theEDITORparameter, above ๐
๐ Tilde expansion
Tilde expansion โ which literally runs in parallel with parameter substitution, no cap โ 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 -, then the value of the HOME, PWD, or OLDPWD parameter is substituted, respectively. Otherwise the password file gets searched for that login name, and the tilde expression is substituted with the user's home directory. If the login name isn't in the password file, or if any quoting or parameter substitution happens in the login name, then no substitution is performed. Nothing. Nada. ๐
In parameter assignments (like the ones preceding a simple-command, or the ones hanging out in the arguments of alias, export, readonly, and typeset), tilde expansion is done after any assignment (i.e. after the equals sign) or after an unquoted colon (:); login names are also delimited by colons.
The home directory of previously expanded login names gets cached and re-used โ iconic efficiency behavior ๐
. 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).
๐ Brace expansion (alternation)
Brace expressions take the following form:
prefix{str1,...,strN}suffix
The expressions are expanded to N words, each of which is the concatenation of prefix, str<sub>i</sub>, and suffix (e.g. a{c,b{X,Y},d}e expands to four words: ace, abXe, abYe, and ade). As noted in the example, brace expressions can be nested and the resulting words are not sorted. Brace expressions must contain an unquoted comma (,) for expansion to occur (e.g. {} and {foo} are not expanded). Brace expansion is carried out after parameter substitution and before file name generation. Order matters, bestie ๐ฆ
๐ธ 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 (and if no files match, the word is left unchanged, no drama). 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 letteraor any digit). In order to represent itself, a-must either be quoted or be the first or last character in the character list. Similarly, a]must be quoted or be the first character in the list if it's gonna 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.
Within a bracket expression, the name of a character class enclosed in [: and :] stands for the list of all characters belonging to that class. Supported character classes:
alnum cntrl lower space
alpha digit print upper
blank graph punct xdigit
These match characters using the macros specified in isalnum(3), isalpha(3), and so on. A character class may not be used as an endpoint of a range. Noted. โจ
[!..]โ like[..], except it matches any character not inside the brackets.*(pattern|...|pattern)โ matches any string of characters that matches zero or more occurrences of the specified patterns. Example: the pattern*(foo|bar)matches the strings"",foo,bar,foobarfoo, etc.+(pattern|...|pattern)โ matches any string of characters that matches one or more occurrences of the specified patterns. Example: the pattern+(foo|bar)matches the stringsfoo,bar,foobar, etc.?(pattern|...|pattern)โ matches the empty string or a string that matches one of the specified patterns. Example: the pattern?(foo|bar)only matches the strings"",foo, andbar.@(pattern|...|pattern)โ matches a string that matches one of the specified patterns. Example: the pattern@(foo|bar)only matches the stringsfooandbar.!(pattern|...|pattern)โ matches any string that does not match one of the specified patterns. Examples: the pattern!(foo|bar)matches all strings exceptfooandbar; the pattern!(*)matches no strings; the pattern!(?)*matches all strings (think about it ๐).
Unlike most shells, ksh never matches . and ... Ever. Periodt.
Also 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're explicitly used in a [..] sequence; and the names . and .. are never matched, even by the pattern .*. The audacity of these directories honestly ๐ญ
If the markdirs option is set, any directories that result from file name generation are marked with a trailing /. Cute little marker, love that for them ๐
๐ 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, iykyk:
- 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 - commands for which any of the following redirections have been specified
And here's the redirection menu, bestie:
> fileโ standard output is redirected to file. If file doesn't exist, it's created; if it does exist, is a regular file, and thenoclobberoption is set, an error occurs; otherwise the file is truncated. Note that this means the commandcmd < foo > foowill openfoofor reading and then truncate it when it opens it for writing, beforecmdgets a chance to actually readfoo. Yeah. It ate itself. ๐>| fileโ same as>, except the file is truncated, even if thenoclobberoption is set. Bold. Iconic. ๐>> fileโ same as>, except if file exists it's appended to instead of being truncated. Also, the file is opened in append mode, so writes always go to the end of the file (seeopen(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. Multitasking queen ๐ซถ<< 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're saved in order. Very organized of them ๐<<- 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 letterp, 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's 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 expanded file name generation characters is used. And heads up: in restricted shells, redirections which can create files cannot be 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're given, so the following will print an error with a line number prepended to it:
$ cat /foo/bar 2>&1 > /dev/null | cat -n
That's the whole point of that example, and it's a vibe check on ordering fr fr ๐ฅ
๐งฎ Arithmetic expressions
Integer arithmetic expressions can be used with the let command, 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.
Expressions 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:
okay so here's the operator roster, top to bottom:
,
= *= /= %= += -= <<= >>= &= ^= |=
||
&&
|
^
&
== !=
< <= >= >
<< >>
+ -
* / %
Ternary operators:
?:โ precedence is immediately higher than assignment.
Grouping operators:
( )โ grouping, bestie.
A parameter that is NULL or unset evaluates to 0. 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. Additionally, integers may be prefixed with 0X or 0x (specifying base 16) or 0 (base 8) in all forms of arithmetic expressions, except as numeric arguments to the test command.
The operators are evaluated as follows:
- unary
+โ result is the argument (included for completeness). - unary
-โ negation. !โ logical NOT; the result is1if argument is zero,0if not.~โ arithmetic (bit-wise) NOT.++โ increment; must be applied to a parameter (not a literal or other expression). The parameter is incremented by1. When used as a prefix operator, the result is the incremented value of the parameter; when used as a postfix operator, the result is the original value of the parameter.--โ similar to++, except the parameter is decremented by1.,โ 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โฉ, with any operator precedence inโจexprโฉpreserved. For example,var1 *= 5 + 3is the same as specifyingvar1 = var1 * (5 + 3).||โ logical OR; the result is1if either argument is non-zero,0if not. The right argument is evaluated only if the left argument is zero.&&โ logical AND; the result is1if both arguments are non-zero,0if not. The right argument is evaluated only if the left argument is non-zero.|โ arithmetic (bit-wise) OR.^โ arithmetic (bit-wise) XOR (exclusive-OR).&โ arithmetic (bit-wise) AND.==โ equal; the result is1if both arguments are equal,0if not.!=โ not equal; the result is0if both arguments are equal,1if not.<โ less than; the result is1if the left argument is less than the right,0if 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 the result isโจarg3โฉ.
๐จ tiny chaos gremlin alert: the sign of % is unspecified if either argument is negative. no cap.
๐ Co-processes
A co-process, which is a pipeline created with the |& operator, is an asynchronous process that the shell can both write to (using print -p) and read from (using read -p). The input and output of the co-process can also be manipulated using >&p and <&p redirections, respectively. Once a co-process has been started, another can't be started until the co-process exits, or until the co-process's input has been redirected using an exec n>&p redirection. If a co-process's input is redirected in this way, the next co-process to be started will share the output with the first co-process, unless the output of the initial co-process has been redirected using an exec n<&p redirection.
Some notes concerning co-processes:
- The only way to close the co-process's input (so the co-process reads an end-of-file) is to redirect the input to a numbered file descriptor and then close that file descriptor e.g.
exec 3>&p; exec 3>&-. - In order for co-processes to share a common output, the shell must keep the write portion of the output pipe open. This means that end-of-file will not be detected until all co-processes sharing the co-process's output have exited (when they all exit, the shell closes its copy of the pipe). This can be avoided by redirecting the output to a numbered file descriptor (as this also causes the shell to close its copy). Note that this behaviour is slightly different from the original Korn shell which closes its copy of the write portion of the co-process output when the most recently started co-process (instead of when all sharing co-processes) exits.
print -pwill ignoreSIGPIPEsignals during writes if the signal is not being trapped or ignored; the same is true if the co-process input has been duplicated to another file descriptor andprint -unis used.
๐งฉ Functions
Functions are defined using either Korn shell function function-name syntax or the Bourne/POSIX shell function-name() syntax (see below for the difference between the two forms). Functions are like .-scripts (i.e. scripts sourced using the . built-in command) in that they are executed in the current environment. However, unlike .-scripts, shell arguments (i.e. positional parameters $1, $2, etc.) are never visible inside them. When the shell is determining the location of a command, functions are searched after special built-in commands, before regular and non-regular built-ins, and before the PATH is searched.
An existing function may be deleted using unset -f function-name. A list of functions can be obtained using typeset +f and the function definitions can be listed using typeset -f. The autoload command (which is an alias for typeset -fu) may be used to create undefined functions: when an undefined function is executed, the shell searches the path specified in the FPATH parameter for a file with the same name as the function, which, if found, is read and executed. If after executing the file the named function is found to be defined, the function is executed; otherwise, the normal command search is continued (i.e. the shell searches the regular built-in command table and PATH). Note that if a command is not found using PATH, an attempt is made to autoload a function using FPATH (this is an undocumented feature of the original Korn shell).
Functions can have two attributes, โtraceโ and โexportโ, which can be set with typeset -ft and typeset -fx, respectively. When a traced function is executed, the shell's xtrace option is turned on for the function's duration; otherwise, the xtrace option is turned off. The โexportโ attribute of functions is currently not used. In the original Korn shell, exported functions are visible to shell scripts that are executed.
Since functions are executed in the current shell environment, parameter assignments made inside functions are visible after the function completes. If this is not the desired effect, the typeset command can be used inside a function to create a local parameter. Note that special parameters (e.g. $$, $!) can't be scoped in this way.
The exit status of a function is that of the last command executed in the function. A function can be made to finish immediately using the return command; this may also be used to explicitly specify the exit status.
Functions defined with the function reserved word are treated differently in the following ways from functions defined with the () notation:
- The
$0parameter is set to the name of the function (Bourne-style functions leave$0untouched). - Parameter assignments preceding function calls are not kept in the shell environment (executing Bourne-style functions will keep assignments).
OPTINDis saved/reset and restored on entry and exit from the function sogetoptscan be used properly both inside and outside the function (Bourne-style functions leaveOPTINDuntouched, so usinggetoptsinside a function interferes with usinggetoptsoutside the function).
๐๏ธ POSIX mode
The shell is intended to be POSIX compliant; however, in some cases, POSIX behaviour is contrary either to the original Korn shell behaviour or to user convenience. How the shell behaves in these cases is determined by the state of the posix option (set -o posix). If it is on, the POSIX behaviour is followed; otherwise, it is not. The posix option is set automatically when the shell starts up if the environment contains the POSIXLY_CORRECT parameter. The shell can also be compiled so that it is in POSIX mode by default; however, this is usually not desirable.
The following is a list of things that are affected by the state of the posix option:
kill -loutput. In POSIX mode, only signal names are listed (in a single line); in non-POSIX mode, signal numbers, names, and descriptions are printed (in columns).echooptions. In POSIX mode,-eand-Eare not treated as options, but printed like other arguments; in non-POSIX mode, these options control the interpretation of backslash sequences.fgexit status. In POSIX mode, the exit status is0if no errors occur; in non-POSIX mode, the exit status is that of the last foregrounded job.evalexit status. Ifevalgets to see an empty command (i.e.eval `false`), its exit status in POSIX mode will be0. In non-POSIX mode, it will be the exit status of the last command substitution that was done in the processing of the arguments toeval(or0if there were no command substitutions).getopts. In POSIX mode, options must start with a-; in non-POSIX mode, options can start with either-or+.- Brace expansion (aka alternation) ๐ โ in POSIX mode it's disabled; in non-POSIX mode it's enabled. Big note tho:
set -o posix(or setting thePOSIXLY_CORRECTparameter) automatically flips thebraceexpandoption off โ but you can totally turn it back on explicitly later, bestie. set -โ in POSIX mode this does not clear theverboseorxtraceoptions; in non-POSIX mode, it does. ๐setexit status โ in POSIX mode, the exit status ofsetis0if there are no errors; in non-POSIX mode, the exit status is that of any command substitutions performed while generating thesetcommand. Example era:set -- \false`; echo $?prints0in POSIX mode,1in non-POSIX mode. <pink>This construct is used in most shell scripts that use the oldgetopt(1)` command. iykyk ๐ญ- Argument expansion of the
alias,export,readonly, andtypesetcommands โ in POSIX mode, normal argument expansion is done; in non-POSIX mode, field splitting, file globbing, brace expansion, and (normal) tilde expansion are turned off, while assignment tilde expansion is turned on. Not me keeping track of all of these ๐ - Signal specification โ in POSIX mode, signals can be specified as digits only if the signal numbers match POSIX values (i.e.
HUP=1,INT=2,QUIT=3,ABRT=6,KILL=9,ALRM=14, andTERM=15); in non-POSIX mode, signals can always be digits. ๐ฆ - Alias expansion โ in POSIX mode, alias expansion is only carried out when reading command words; in non-POSIX mode, alias expansion is carried out on any word following an alias that ended in a space. For example, the following
forloop uses parameter i in POSIX mode and j in non-POSIX mode, and yes that's the whole point of the demo โจ
alias a='for ' i='j'
a i in 1 2; do echo i=$i j=$j; done
๐ธ Strict Bourne shell mode ๐ธ
When the sh option is enabled (see the set command), ksh will behave like sh(1) in the following ways โ like it's cosplaying a classic, lowkey iconic:
- The parameter
$_is not set to:- the expanded alias' full program path after entering commands that are tracked aliases
- the last argument on the command line after entering external commands
- the file that changed when
MAILPATHis set to monitor a mailbox
- File descriptors are left untouched when executing
execwith no arguments. ๐ซถ - Backslash-escaped special characters are not substituted in
PS1. - Sequences of
((...))are not interpreted as arithmetic expressions. no math for you, bestie ๐
๐ 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 โ top to bottom, no skipping. ๐
Special built-in commands differ from other commands in that:
- the
PATHparameter is not used to find them, - an error during their execution can cause a non-interactive shell to exit, and
- parameter assignments that are specified before the command are kept after the command completes.
Just to confuse things ๐ญ โ if the posix option is turned off (see the 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. That's the whole difference, periodt.
The original ksh and POSIX differ somewhat in which commands are considered special or regular:
POSIX special commands
., :, break, continue, eval, exec, exit, export, readonly, return, set, shift, times, trap, unset
Additional ksh special commands
builtin, typeset
Very special commands (when POSIX mode is off)
alias, readonly, set, typeset
POSIX regular commands
alias, bg, cd, command, false, fc, fg, getopts, jobs, kill, pwd, read, true, umask, unalias, wait
Additional ksh regular commands
[, echo, let, print, suspend, test, ulimit, whence
Once the type of command has been determined, any command-line parameter assignments are performed and exported for the duration of the command.
The following describes the special and regular built-in commands โ this is the good part, grab a snack ๐:
. file [arg ...]
Execute the commands in file in the current environment. The file is searched for in the directories of PATH. If arguments are given, the positional parameters may be used to access them while file is being executed. If no arguments are given, the positional parameters are those of the environment the command is used in. ๐
: [...]
The null command. Exit status is set to zero. Literally does nothing and slays at it. ๐
alias [-d | -t [-r] | +-x] [-p] [+] [name[=value] ...]
Without arguments, alias lists all aliases. For any name without a value, the existing alias is listed. Any name with a value defines an alias (see "Aliases" above).
When listing aliases, one of two formats is used. Normally, aliases are listed as name=value, where value is quoted. If options were preceded with +, or a lone + is given on the command line, only name is printed.
The -d option causes directory aliases, which are used in tilde expansion, to be listed or set (see "Tilde expansion" above). ๐
If the -p option is used, each alias is prefixed with the string alias .
The -t option indicates that tracked aliases are to be listed/set (values specified on the command line are ignored for tracked aliases). The -r option indicates that all tracked aliases are to be reset.
The -x option sets (+x clears) the export attribute of an alias or, if no names are given, lists the aliases with the export attribute (exporting an alias has no effect โ it's giving decorative, ngl).
bg [job ...]
Resume the specified stopped job(s) in the background. If no jobs are specified, %+ is assumed. See "Job control" below for more information. ๐ฆ
bind [-l]
The current bindings are listed. If the -l flag is given, bind instead lists the names of the functions to which keys may be bound. See "Emacs editing mode" for more information. ๐
bind [-m] string=[substitute] ...
bind string=[editing-command] ...
In "Emacs editing mode", the specified editing command is bound to the given string. Future input of the string will cause the editing command to be immediately invoked. Bindings have no effect in "Vi editing mode". ๐
If the -m flag is given, the specified input string will afterwards be immediately replaced by the given substitute string, which may contain editing commands. Control characters may be written using caret notation. For example, ^X represents Control+X. โจ
If a certain character occurs as the first character of any bound multi-character string sequence, that character becomes a command prefix character. Any character sequence that starts with a command prefix character but that is not bound to a command or substitute is implicitly considered as bound to the error command. By default, two command prefix characters exist: Escape (^[) and Control-X (^X). ๐
The following default bindings show how the arrow keys on an ANSI terminal or xterm are bound (of course some escape sequences won't work out quite this nicely):
bind '^[[A'=up-history
bind '^[[B'=down-history
bind '^[[C'=forward-char
bind '^[[D'=backward-char
break [level]
Exit the levelth inner-most for, select, until, or while loop. level defaults to 1. ๐ซถ
builtin command [arg ...]
Execute the built-in command command. That's it, that's the whole vibe. โญ
cd [-LP] [dir]
Set the working directory to dir. If the parameter CDPATH is set, it lists the search path for the directory containing dir. A NULL path or . means the current directory. If dir is found in any component of the CDPATH search path other than the NULL path, the name of the new working directory will be written to standard output. If dir is missing, the home directory HOME is used. If dir is -, the previous working directory is used (see the OLDPWD parameter). ๐
If the -L option (logical path) is used or if the physical option isn't set (see the set command below), references to .. in dir are relative to the path used to get to the directory. If the -P option (physical path) is used or if the physical option is set, .. is relative to the filesystem directory tree. The PWD and OLDPWD parameters are updated to reflect the current and old working directory, respectively. ๐ฅ
cd [-LP] old new
The string new is substituted for old in the current directory, and the shell attempts to change to the new directory. Search-and-replace but make it a directory change, obsessed. ๐ธ
command [-pVv] cmd [arg ...]
If neither the -v nor -V option is given, cmd is executed exactly as if command had not been specified, with two exceptions: firstly, cmd cannot be an alias or a shell function; and secondly, special built-in commands lose their specialness (i.e. redirection and utility errors do not cause the shell to exit, and command assignments are not permanent). ๐
If the -p option is given, a default search path is used instead of the current value of PATH (the actual value of the default path is system dependent: on POSIX-ish systems, it is the value returned by getconf PATH). Nevertheless, reserved words, aliases, shell functions, and builtin commands are still found before external commands. ๐
If the -v option is given, instead of executing cmd, information about what would be executed is given (and the same is done for arg ...). For special and regular built-in commands and functions, their names are simply printed; for aliases, a command that defines them is printed; and for commands found by searching the PATH parameter, the full path of the command is printed. If no command is found (i.e. the path search fails), nothing is printed and command exits with a non-zero status. The -V option is like the -v option, except it is more verbose. ๐
continue [level]
Jumps to the beginning of the levelth inner-most for, select, until, or while loop. level defaults to 1. ๐
echo [-Een] [arg ...]
Bestie, this is the โจclassicโจ. It prints its args to standard output, separated by spaces, and then hits you with a newline. Adorable. But plot twist: if any of the arguments contain the backslash sequence '\c', that trailing newline gets suppressed ๐ถ (it justโฆ doesn't happen). Wanna know the other backslash sequences it recognizes? Scroll down to the print command, babe, it's all there ๐
The options exist purely for compatibility with BSD shell scripts, iykyk:
-nโ suppresses the trailing newline.-eโ enables backslash interpretation (which is a total no-op, because that's normally done anyway ๐).-Eโ suppresses backslash interpretation.
Extra credit: if the posix option is set, only the first argument is treated as an option โ and like, only if it is exactly "-n". No vibes, no exceptions.
eval command ...
Takes all its arguments, smashes them together into one single string (with spaces between them, obvs), and then the shell parses and executes that string in the current environment. It's giving main-character string that becomes real. โจ
exec [command [arg ...]]
Runs the command without forking โ it literally replaces the shell process. Like, the shell hands over the aux and dips ๐.
If no command is given except for I/O redirection, then that I/O redirection is permanent and the shell is not replaced. And heads up ๐ซถ: any file descriptors greater than 2 that get opened or dup(2)'d this way are not made available to other executed commands (i.e. commands that aren't built-in to the shell). Also not me calling out the Bourne shell, but it differs here โ it does pass these file descriptors on. ๐
exit [status]
The shell exits with the specified exit status. If status isn't specified, it just dips with the current value of the $? parameter. Simple, iconic, goodbye. ๐ฆ
export [-p] [parameter[=value]]
Sets the export attribute on the named parameters. Exported parameters get passed along in the environment to executed commands โ think of it as them getting a VIP pass to every party ๐. If values are specified, the named parameters are also assigned.
No parameters specified? Then the names of all parameters with the export attribute are printed, one per line โ unless you use -p, in which case you get full export commands defining all exported parameters, including their values. Bougie printout, honestly. ๐
false
A command that exits with a non-zero status. That's it. That's the whole personality. It's the hater of the builtin world and we respect it. ๐
fc [-e editor | -l [-n]] [-r] [first [last]]
Fix command โ yes, "fc" stands for that, slay for the naming committee. first and last select commands from the history. You can select them by history number, or by a string โ and it'll grab the most recent command starting with that string. So specific. So efficient. ๐
-lโ lists the command on standard output.-nโ inhibits the default command numbers.-rโ reverses the order of the list.
Without -l, the selected commands get edited by the editor you specified with -e, or โ if there's no -e โ the editor specified by the FCEDIT parameter (and if that parameter isn't set, /bin/ed is used, bestie, that's the fallback ๐ซฃ), and then the shell executes them.
fc -s [-g] [old=new] [prefix]
Re-executes the most recent command beginning with prefix โ or the previous command if you don't give a prefix โ while performing the optional substitution of old with new. If -g is specified, all occurrences of old get replaced with new. No editor is invoked when the -s flag is used ๐
โโ๏ธ. The obsolescent equivalent "-e -" is also accepted (aging gracefully, we love to see it). This command is usually accessed with the predefined alias r='fc -s' โ honestly the glow-up. ๐
fg [job ...]
Resumes the specified job(s) in the foreground. No jobs specified? %+ is assumed, periodt. Peep "Job control" below for more info. ๐ฅ
getopts optstring name [arg ...]
This one's the people's princess of shell procedures ๐ โ it parses the specified arguments (or the positional parameters, if you don't give it any arguments) and checks for legal options.
optstring contains the option letters that getopts is supposed to recognize. If a letter is followed by a colon, that option is expected to have an argument. Options that don't take arguments may be grouped together in a single argument. And if an option takes an argument and the option character is not the last character of the argument it was found in, the remainder of that argument is taken to be the option's argument; otherwise, the next argument is the option's argument. Little logic puzzle, love that for us ๐ง
Every time getopts is invoked, it places the next option in the shell parameter name, and the index of the argument to be processed by the next call to getopts goes in the shell parameter OPTIND. If the option was introduced with a '+', the option placed in name gets prefixed with a '+'. And when an option requires an argument, getopts drops it into the shell parameter OPTARG. ๐ซ
When an illegal option or a missing option argument shows up, a question mark or a colon is placed in name โ indicating an illegal option or missing argument, respectively โ and OPTARG is set to the option character that caused the whole problem ๐ญ. Furthermore, if optstring does not begin with a colon, a question mark is placed in name, OPTARG is unset, and an error message is printed to standard error.
When the end of the options is encountered, getopts exits with a non-zero exit status. Options end at the first (non-option argument) argument that does not start with a '-', or when a '--' argument is encountered. ๐
Option parsing can be reset by setting OPTIND to 1 โ and this is done automatically whenever the shell or a shell procedure is invoked, no notes.
โ ๏ธ Warning, bestie: changing the value of the shell parameterOPTINDto a value other than1, or parsing different sets of arguments without resettingOPTIND, may lead to unexpected results. Like, do not do that to yourself.
The following code fragment shows how one might process the arguments for a command that can take the option -a and the option -o, which requires an argument. Study it, it's literally the blueprint ๐โจ
while getopts ao: name
do
case $name in
a) flag=1 ;;
o) oarg=$OPTARG ;;
?) echo "Usage: ..."; exit 2 ;;
esac
done
shift $(($OPTIND - 1))
echo "Non-option arguments: " "$@"
hash [-r] [name ...]
With no arguments, any hashed executable command pathnames get listed. The -r option causes all hashed commands to be removed from the hash table โ a full cleanse, we love a reset ๐งผ. Each name is searched as if it were a command name and added to the hash table if it's an executable command. ๐
jobs [-lnp] [job ...]
Displays info about the specified job(s); if you specify none, all jobs are displayed. FOMO-proof.
-nโ info is displayed only for jobs that have changed state since the last notification. It's giving "only the tea that's new" ๐.-lโ the process ID of each process in a job is also listed.-pโ only the process group of each job gets printed.
See "Job control" below for the format of job and the displayed job. ๐
kill [-s signame | -signum | -signame] { job | pid | pgrp } ...
Sends the specified signal to the specified jobs, process IDs, or process groups ๐. If no signal is specified, the TERM signal is sent. If a job is specified, the signal gets sent to that job's process group. See "Job control" below for the format of job. Dramatic, effective, iconic.
kill -l [exit-status ...]
Prints the signal name corresponding to exit-status. If no arguments are specified, a list of all the signals is printed โ with their numbers and a short description of them. Reference material, but make it cute. ๐
let [expression ...]
Each expression is evaluated (peep "Arithmetic expressions" above). If all expressions are successfully evaluated, the exit status is 0 (1) if the last expression evaluated to non-zero (zero) โ yes, that's the actual order, read it twice, it's real ๐ญ. If an error occurs during the parsing or evaluation of an expression, the exit status is greater than 1.
Since expressions may need to be quoted, (( expr )) is syntactic sugar for let "expr". Short, sweet, slay. ๐ฌ
print [-nprsu[n] | -R [-en]] [argument ...]
print prints its arguments on standard output, separated by spaces and terminated with a newline. The basics, but make it โจ.
-nโ suppresses the newline.-rโ inhibits the'\'expansion.-sโ prints to the history file instead of standard output.-un โ prints to file descriptor n (n defaults to1if omitted).-pโ prints to the co-process (see "Co-processes" above). ๐ซ
By default, certain C escapes get translated, and here's the exact list, no gatekeeping: '\b', '\f', '\n', '\r', '\t', '\v', and '\0###' ('#' is an octal digit, of which there may be 0 to 3). Also '\c' is equivalent to using the -n option. ๐
The -R option is used to emulate, to some degree, the BSD echo(1) command โ which does not process '\' sequences unless the -e option is given. As above, the -n option suppresses the trailing newline. Compatibility queen ๐.
pwd [-LP]
Prints the present working directory. ๐
- If the
-Loption is used, or if thephysicaloption isn't set (see thesetcommand below), the logical path is printed โ i.e. the path used tocdto the current directory. Vibes-based, but valid. - If the
-Poption (physical path) is used, or if thephysicaloption is set, the path determined from the filesystem is printed โ by following'..'directories all the way up to the root directory. Cold hard facts. ๐งญ
read [-prsu[n]] [parameter ...]
Reads a line of input from standard input, separates that line into fields using the IFS parameter (see "Substitution" above), and assigns each field to the specified parameters. ๐ซถ
Here's the field math, bestie: if there are more parameters than fields, the extra parameters are set to NULL โ or, alternatively, if there are more fields than parameters, the last parameter gets assigned the remaining fields (inclusive of any separating spaces). If no parameters are specified, the REPLY parameter is used. ๐
And if the input line ends in a backslash and the -r option was not used, the backslash and the newline get stripped and more input is read. Multi-line moment. ๐ If no input is read, read exits with a non-zero status. ๐
The first parameter can also have a question mark with a string tacked onto it โ and oml that string becomes a prompt ๐ฌ (it gets printed to standard error before anything is read) but only if the input is a tty(4). Like: read nfoo?'number of foos: '.
The -un and -p options make input come from file descriptor n (n defaults to 0 if you leave it out) or from the current co-process, respectively (peep โCo-processesโ above for the tea on that one โ). And if you use the -s option, the input gets saved to the history file. โจ
๐ readonly ๐
readonly [-p] [parameter[=value] ...]
Locks the read-only attribute onto the named parameters ๐. If you hand it values, the parameters get set to those values before the attribute gets slapped on. And once a parameter is made read-only, that's it โ bestie, it cannot be unset and its value cannot be changed. Periodt.
If you don't specify any parameters, it prints the names of all the parameters rockin' the read-only attribute, one per line โ unless you use the -p option, in which case it prints readonly commands that define all the read-only parameters, values included. ๐
๐ฆ return ๐ฆ
return [status]
Dips out of a function or a . script, with exit status status. If you don't give a status, it uses the exit status of the last command that ran. And if you use it outside of a function or . script? It does the exact same thing as exit. ๐ญ
Heads up:kshtreats both profile andENVfiles as.scripts, whereas the original Korn shell only treats profiles as.scripts. Not me pointing out the glow-up ๐
โจ set โจ
set [+-abCefhkmnpsuvXx] [+-o option] [+-A name] [--] [arg ...]
Okay so set is the multitasker of the friend group ๐ โ it can set (-) or clear (+) shell options, set the positional parameters, or set an array parameter. You can flip options with the +-o option syntax, where option is the long name of an option, or with the +-letter syntax, where letter is the option's single letter name (and no, not every option has a single letter name, don't come for me ๐ซถ).
Here's the whole lineup โ option letters (if they even exist) and long names, plus what each one actually does:
-Aname โ Sets the elements of the array parameter name toarg .... If-Ais used, the array is reset (i.e. emptied) first ๐งน; if+Ais used, the first N elements get set (where N is the number of arguments) and the rest are left untouched.-a|allexportโ All new parameters are created with the export attribute.-b|notifyโ Print job notification messages asynchronously, instead of just before the prompt. Only used if job control is enabled (-m).-C|noclobberโ Stops>redirection from overwriting existing files ๐ซ. Instead, you gotta use>|to force the overwrite.-e|errexitโ Exit (after executing theERRtrap) as soon as an error happens or a command fails (i.e. exits with a non-zero status). This does not apply to commands whose exit status is explicitly tested by a shell construct likeif,until,while, or!statements. For&&or||, only the status of the last command is tested. ๐ฅ-f|noglobโ Do not expand file name patterns.-h|trackallโ Create tracked aliases for all executed commands (see โAliasesโ above). Enabled by default for non-interactive shells.-k|keywordโ Parameter assignments are recognized anywhere in a command.-m|monitorโ Enable job control (default for interactive shells).-n|noexecโ Do not execute any commands. Handy for checking the syntax of scripts (ignored if interactive).-p|privilegedโ The shell is a privileged shell ๐. It gets set automatically if, when the shell starts, the real UID or GID does not match the effective UID (EUID) or GID (EGID), respectively. See above for what that actually means.-s|stdinโ If used when the shell is invoked, commands are read from standard input. Set automatically if the shell is invoked with no arguments.
When -s is used with the set command, it causes the specified arguments to be sorted before assigning them to the positional parameters (or to the array name, if -A is used). ๐ค
-u|nounsetโ Referencing an unset parameter is treated as an error ๐ฑ โ unless one of the-,+, or=modifiers is used.-v|verboseโ Write shell input to standard error as it is read.-X|markdirsโ Mark directories with a trailing/during file name generation.-x|xtraceโ Print commands and parameter assignments when they are executed, preceded by the value ofPS4.bgniceโ Background jobs are run with lower priority.braceexpandโ Enable brace expansion (a.k.a. alternation).csh-historyโ Enables a subset ofcsh(1)-style history editing using the!character.emacsโ Enable BRL emacs-like command-line editing (interactive shells only); see โEmacs editing modeโ.gmacsโ Enable gmacs-like command-line editing (interactive shells only). Currently identical toemacsediting, except thattranspose(^T) acts slightly differently.ignoreeofโ The shell will not (easily) exit when end-of-file is read;exitmust be used. And to avoid infinite loops, the shell will exit if EOF is read 13 times in a row ๐.interactiveโ The shell is an interactive shell. This option can only be used when the shell is invoked. See above for what that means.loginโ The shell is a login shell. This option can only be used when the shell is invoked. See above for what that means.nohupโ Do not kill running jobs with aSIGHUPsignal when a login shell exits. Currently set by default; this is different from the original Korn shell (which doesn't have this option, but does send theSIGHUPsignal).nologโ No effect. In the original Korn shell, this prevents function definitions from being stored in the history file. ๐physicalโ Causes thecdandpwdcommands to use โphysicalโ (i.e. the filesystem's)..directories instead of โlogicalโ directories (i.e. the shell handles.., which lets the user be oblivious of symbolic links to directories). Clear by default. Also note: setting this option does not affect the current value of thePWDparameter; only thecdcommand changesPWD. See thecdandpwdcommands above for more deets. ๐๏ธpipefailโ The exit status of a pipeline is the exit status of the rightmost command in the pipeline that doesn't return0, or0if all commands returned a0exit status. Slay.posixโ Enable POSIX mode. See โPOSIX modeโ above.restrictedโ The shell is a restricted shell. This option can only be used when the shell is invoked. See above for what that means.shโ Enable strict Bourne shell mode (see โStrict Bourne shell modeโ above).viโ Enablevi(1)-like command-line editing (interactive shells only).vi-esccompleteโ In vi command-line editing, do command and file name completion when escape (^[) is entered in command mode.vi-show8โ Prefix characters with the eighth bit set withM-. If this option is not set, characters in the range128-160are printed as is, which may cause problems. ๐ฌvi-tabcompleteโ In vi command-line editing, do command and file name completion when tab (^I) is entered in insert mode. This is the default.virawโ No effect. In the original Korn shell, unlessvirawwas set, the vi command-line mode would let thetty(4)driver do the work until ESC (^[) was entered.kshis always invirawmode. ๐
These options can also be used upon invocation of the shell ๐. The current set of options (the ones with single letter names) can be found in the parameter $-. And set -o with no option name will list all the options and whether each one is on or off; set +o prints the current shell options in a form you can reinput to the shell to achieve the exact same option settings. Recycling, but make it shell โจ.
Remaining arguments, if there are any, are positional parameters and get assigned, in order, to the positional parameters (i.e. $1, $2, etc.). If options end with -- and there are no remaining arguments, all positional parameters are cleared ๐งผ. If no options or arguments are given, the values of all names are printed. And for unknown historical reasons, a lone - option is treated specially โ it clears both the -x and -v options. Don't ask, iykyk ๐
shift [number]โ renames the positional parameters, bestie:number+1becomes1,number+2becomes2, and so on down the line. If you don't pass anumber, it just defaults to1โจsuspendโ puts the shell on pause, like it just got smacked with the suspend character from the terminal ๐ Heads up though: you cannot suspend a login shell unless the parent process is in the same terminal session but a different process group. General vibe rule โ if the shell was started by another shell or viasu(1), it can be suspended, no cap ๐ซถtest expression/[ expression ]โ evaluates the expression and gives you back zero status if true,1if false, or something greater than1if it errored out ๐ญ Normally you see it as the condition command ofifandwhilestatements. Also: symbolic links get followed for all file expressions except-hand-L. Iconic. Now here's the whole basic expression menu โฌ๏ธ-a fileโfileexists.-b fileโfileis a block special device.-c fileโfileis a character special device.-d fileโfileis a directory.-e fileโfileexists.-f fileโfileis a regular file.-G fileโfile's group is the shell's effective group ID.-g fileโfile's mode has the setgid bit set.-h fileโfileis a symbolic link.-k fileโfile's mode has thesticky(8)bit set.-L fileโfileis a symbolic link.-O fileโfile's owner is the shell's effective user ID.-o optionโ the shell option is set (peep thesetcommand above for the full list of options). Non-standard extension flex: if the option starts with a!, the test gets negated ๐ and the test always fails if the option doesn't exist (so[ -o foo -o -o !foo ]returns true if and only if optionfooexists).-p fileโfileis a named pipe.-r fileโfileexists and is readable.-S fileโfileis aunix(4)-domain socket.-s fileโfileis not empty.-t fdโ file descriptorfdis atty(4)device.-u fileโfile's mode has the setuid bit set.-w fileโfileexists and is writable.-x fileโfileexists and is executable.file1 -nt file2โfile1is newer thanfile2, orfile1exists andfile2does not.file1 -ot file2โfile1is older thanfile2, orfile2exists andfile1does not.file1 -ef file2โfile1is literally the same file asfile2.stringโstringhas non-zero length.-n stringโstringis not empty.-z stringโstringis empty.string = stringโ strings are equal.string == stringโ strings are equal.string != stringโ strings are not equal.string > stringโ strings compare greater than, based on the ASCII value of their characters.string < stringโ strings compare less than, based on the ASCII value of their characters.number -eq numberโ numbers compare equal.number -ne numberโ numbers compare not equal.number -ge numberโ numbers compare greater than or equal.number -gt numberโ numbers compare greater than.number -le numberโ numbers compare less than or equal.number -lt numberโ numbers compare less than.
All those basic expressions โ where unary operators outrank binary operators, obviously ๐ โ can be combined with these operators, listed in increasing order of precedence:
expr -o expr Logical OR.
expr -a expr Logical AND.
! expr Logical NOT.
( expr ) Grouping.
Okay so on operating systems that don't support /dev/fd/n devices (where n is a file descriptor number), test will attempt to fake it for all the tests that operate on files โ except the -e test, she sits that one out ๐ For example, [ -w /dev/fd/2 ] tests if file descriptor 2 is writable. Sneaky but slay.
Heads up, some special rules apply (courtesy of POSIX, ty bestie) if the number of arguments totestor[ ... ]is less than five: if leading!arguments can be stripped such that only one argument remains, then a string length test is performed (again, even if the argument is a unary operator); if leading!arguments can be stripped such that three arguments remain and the second argument is a binary operator, then the binary operation is performed (even if the first argument is a unary operator, including an unstripped!). It's giving chaos but it's the rules ๐
Note: a super common mistake is usingif [ $foo = bar ], which fails if the parameterfoois NULL or unset, if it has embedded spaces (i.e.IFScharacters), or if it's a unary operator like!or-n. Do tests likeif [ "X$foo" = Xbar ]instead โ trust, this is the way ๐ซถ
time [-p] [pipeline]โ if you hand it apipeline, it reports the times used to execute that pipeline. If you give it no pipeline, it reports the user and system time used by the shell itself and all the commands it's run since it started โฑ๏ธ The times reported are the real time (elapsed, start to finish), the user CPU time (time spent running in user mode), and the system CPU time (time spent running in kernel mode). Times go to standard error, and the output format is:
0m0.00s real 0m0.00s user 0m0.00s system
If the -p option is given, the output gets a little longer:
real 0.00
user 0.00
sys 0.00
It is an error to specify the -p option unless pipeline is a simple command ๐จ
Also, simple redirections of standard error do not affect the output of the time command:
$ time sleep 1 2> afile
$ { time sleep 1; } 2> afile
Times for the first command do not go to afile, but those of the second command do. The way that difference matters, iykyk ๐
timesโ prints the accumulated user and system times used both by the shell and by processes the shell started that have since exited. The output format is:
0m0.00s 0m0.00s
0m0.00s 0m0.00s
trap [handler signal ...]โ sets a trap handler that gets executed when any of the specified signals are received ๐ชคhandleris either a NULL string, meaning the signals are to be ignored, a minus sign (-), meaning the default action is to be taken for the signals (seesignal(3)), or a string containing shell commands to be evaluated and executed at the first opportunity (i.e. when the current command completes, or before printing the nextPS1prompt) after receipt of one of the signals. Andsignalis the name of a signal (e.g.PIPEorALRM) or the number of the signal (see thekill -lcommand above).
There are two special signals, and they're kind of the main characters here โจ EXIT (also known as 0), which is executed when the shell is about to exit, and ERR, which is executed after an error occurs (an error being something that would cause the shell to exit if the -e or errexit option were set โ see the set command above). EXIT handlers are executed in the environment of the last executed command. Note that for non-interactive shells, the trap handler cannot be changed for signals that were ignored when the shell started ๐
With no arguments, trap lists, as a series of trap commands, the current state of the traps that have been set since the shell started. Note that the output of trap cannot be usefully piped to another process (an artifact of the fact that traps are cleared when subprocesses are created โ sad but true ๐ญ).
The original Korn shell's DEBUG trap and the handling of ERR and EXIT traps in functions are not yet implemented. Don't come for me, that's just what the page says ๐
trueโ a command that exits with a zero value. That's it. That's the whole personality ๐ธtypeโ short form ofcommand -V(see above). So convenient, obsessed ๐typeset [[+-lprtUux] [-L[n]] [-R[n]] [-Z[n]] [-i[n]] | -f [-tux]] [name[=value] ...]โ display or set parameter attributes ๐
With no name arguments, parameter attributes are displayed: if no options are used, the current attributes of all parameters are printed as typeset commands; if an option is given (or - with no option letter), all parameters and their values with the specified attributes are printed; if options are introduced with +, parameter values are not printed.
If name arguments are given, the attributes of the named parameters are set (-) or cleared (+). Values for parameters may optionally be specified. And if typeset is used inside a function, any newly created parameters are local to the function ๐ซถ
When -f is used, typeset operates on the attributes of functions. As with parameters, if no name arguments are given, functions are listed with their values (i.e. definitions) unless options are introduced with +, in which case only the function names are reported.
-fโ Function mode. Display or set functions and their attributes, instead of parameters.-i[n]โ Integer attribute.nspecifies the base to use when displaying the integer (if not specified, the base given in the first assignment is used). Parameters with this attribute may be assigned values containing arithmetic expressions.-L[n]โ Left justify attribute.nspecifies the field width. Ifnis not specified, the current width of a parameter (or the width of its first assigned value) is used. Leading whitespace (and zeros, if used with the-Zoption) is stripped. If necessary, values are either truncated or space padded to fit the field width.
-lโ lower case attribute ๐ any ALL-CAPS characters in your values get converted to lowercase. (Lowkey a glow-down for your data, but okay.) Fun lore: in the original Korn shell this parameter meant "long integer" when you used it with-i. She's had a rebrand โจ-pโ print completetypesetcommands that can be used to re-create the attributes of parameters โ note: the attributes, not the values. This is the default action, and yes, the option exists purely forksh93compatibility ๐ซถ-R[n]โ right justify attribute, bestie.nsets the field width. If you don't specifyn, the current width of the parameter gets used (or the width of its first assigned value). Trailing whitespace is stripped. And if things don't fit? Values either get stripped of leading characters or space-padded so they squeeze into the field width. It's giving tailoring ๐-rโ read-only attribute ๐ parameters with this can't be assigned to or unset. And the real drama: once this attribute is set, it cannot be turned off. Periodt. No take-backs.-tโ tag attribute. Has no meaning to the shell, it's just provided for application use. (A little decorative accessory for your own programs, cute.)
For functions, -t is the trace attribute ๐ when functions with the trace attribute are executed, the xtrace (-x) shell option is temporarily turned on.
-Uโ unsigned integer attribute. Integers print as unsigned values (only useful when combined with the-ioption). Heads up: this option is not in the original Korn shell, she's an exclusive ๐-uโ upper case attribute. All lowercase characters in values get converted to UPPERCASE. (In the original Korn shell this parameter meant "unsigned integer" when used with-i, which meant upper case letters would never be used for bases greater than 10 โ see the-Uoption. History lesson over, you're welcome ๐)
For functions, -u is the undefined attribute. See "Functions" above for the implications of this, iykyk.
-xโ export attribute. Parameters (or functions) get placed in the environment of any executed commands. Warning bestie: exported functions are not yet implemented ๐-Z[n]โ zero fill attribute. If it's not combined with-L, this is the same as-R, except zero padding is used instead of space padding. Same energy, different filler ๐
๐งฑ ulimit โ display or set process limits
ulimit [-acdfHlmnpSst [value]] ...
Display or set process limits. If you don't use any options, the file size limit (-f) is assumed. value, if you specify it, can be either an arithmetic expression starting with a number or the word unlimited ๐
The limits affect the shell and any processes created by the shell after a limit is imposed. And the key bit: limits may not be increased once they are set. So think before you commit, bestie, this is not a casual decision ๐ญ
-aโ display all limits; unless-His used, soft limits are what's shown ๐-c nโ impose a size limit ofnblocks on the size of core dumps.-d nโ impose a size limit ofnkilobytes on the size of the data area.-f nโ impose a size limit ofnblocks on files written by the shell and its child processes (files of any size may be read, so reading is unbothered ๐ ).-Hโ set the hard limit only (the default is to set both hard and soft limits).-l nโ impose a limit ofnkilobytes on the amount of locked (wired) physical memory.-m nโ impose a limit ofnkilobytes on the amount of physical memory used. Ngl, this limit is not enforced ๐ so it's purely decorative.-n nโ impose a limit ofnfile descriptors that can be open at once.-p nโ impose a limit ofnprocesses that can be run by the user at any one time.-Sโ set the soft limit only (the default is to set both hard and soft limits).-s nโ impose a size limit ofnkilobytes on the size of the stack area.-t nโ impose a time limit ofnCPU seconds spent in user mode to be used by each process.
As far asulimitis concerned, a block is512bytes. The more you know โญ
๐ญ umask โ display or set the file permission creation mask
umask [-S] [mask]
Display or set the file permission creation mask, or umask (see umask(2)). If you use the -S option, the mask displayed or set is symbolic; otherwise it's an octal number ๐ข
Symbolic masks are like the ones chmod(1) uses. When used, they describe what permissions may be made available โ as opposed to octal masks, where a set bit means the corresponding bit is to be cleared. Opposite day, but make it permissions ๐
For example, ug=rwx,o= sets the mask so files will not be readable, writable, or executable by "others", and it's equivalent (on most systems) to the octal mask 007. Slay, you learned a thing ๐
๐งน unalias โ yeet those aliases
unalias [-adt] [name ...]
The aliases for the given names are removed. If you use -a, all aliases are removed (nuclear option, iconic ๐
). If you use -t or -d, the indicated operations are carried out on tracked or directory aliases, respectively.
๐๏ธ unset โ remove parameters or functions
unset [-fv] parameter ...
Unset the named parameters (-v, the default) or functions (-f). The exit status is non-zero if any of the parameters have the read-only attribute set, and zero otherwise. So if something refuses to be unset, that's her being read-only, not her being difficult ๐
โณ wait โ wait for jobs to finish
wait [job ...]
Wait for the specified job(s) to finish. The exit status of wait is that of the last specified job.
- If the last job was killed by a signal, the exit status is
128+ the number of the signal (seekill -lexit-status above). - If the last specified job can't be found (because it never existed, or it had already finished), the exit status of
waitis127.
See "Job control" below for the format of job. wait will return if a signal for which a trap has been set is received, or if a SIGHUP, SIGINT, or SIGQUIT signal is received ๐ก
If no jobs are specified, wait waits for all currently running jobs (if any) to finish and exits with a zero status. If job monitoring is enabled, the completion status of jobs is printed โ this is not the case when jobs are explicitly specified, jsyk ๐
๐ whence โ where does this command even come from
whence [-pv] [name ...]
For each name, the type of command is listed: reserved word, built-in, alias, function, tracked alias, or executable. It's giving ancestry dot com ๐งฌ
If you use the -p option, a path search is performed even if name is a reserved word, alias, etc.
Without -v, whence is similar to command -v, except that whence won't print aliases as alias commands. With -v, whence is the same as command -V.
Careful bestie: forwhence, the-poption does not affect the search path used, the way it does forcommand. Different builtin, different rules ๐ซถ
If the type of one or more of the names could not be determined, the exit status is non-zero.
๐ฎ Job control ๐ฎ
Job control refers to 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 display this info with the jobs commands ๐
If job control is fully enabled (using set -m or set -o monitor), as it is for interactive shells, 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, and the state of the terminal is saved or restored when a foreground job is stopped or restarted, respectively. The terminal remembers where it left off, main character energy ๐
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. Soz ๐ญ
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 the 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, and honestly this is lowkey the most fun part:
%+|%%|%โ the most recently stopped job or, if there are no stopped jobs, the oldest running job. The default fave โจ%-โ the job that would be the%+job if the latter did not exist. The understudy ๐%nโ the job with job numbern.%?stringโ the job with its command containing the string string (an error occurs if multiple jobs are matched โ so be specific, bestie).%stringโ the job with its command starting with the 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 the+or-character if the job is the%+or%-job, respectively, or space if it is neither;statusโ indicates the current state of the job and can be:Done [number]โ the job exited. number is the exit status of the job, which is omitted if the status is zero. Clean exit, no notes ๐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 ๐).Stopped [signal]โ the job was stopped by the indicated signal (if no signal is given, the job was stopped bySIGTSTP).- signal-description [
"core dumped"] โ the job was killed by a signal (e.g. memory fault, hangup); usekill -lfor 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, each process will have a line showing its command and possibly its status, if it is different from the status of the previous process ๐ธ
...and if you try to bail while you've got jobs sitting there in the stopped state, the shell is gonna be like "bestie, no" โ it warns you about the stopped jobs and refuses to exit. But if you immediately try to exit again? The stopped jobs get a SIGHUP and the shell dips out. Same energy for login shells: if the nohup option isn't set and you've got running jobs when you try to exit a login shell, it warns you and holds the door shut. Try again right away and those running jobs catch a SIGHUP and the shell exits. Rude? Maybe. But that's the deal. ๐
Interactive input line editing
Okay so this is the fun part ๐ โ the shell can read command lines from a tty(4) in an interactive session in three different modes, and they're controlled by the emacs, gmacs, and vi options. Quick vibe check: you can set at most one of these at a time, no cap.
The default is emacs. You can set the editing modes explicitly with the set built-in, or sneakily/implicitly via the EDITOR and VISUAL environment variables. And if none of these options are enabled? The shell just reads lines using the normal tty(4) driver, plain and simple. If emacs or gmacs is set, you get emacs-like editing of the command; if vi is set, you get vi-like editing. Both modes get described in detail in the following sections, iykyk. โจ
In these editing modes, if a line is longer than the screen width (check the COLUMNS parameter), a > , +, or < character shows up in the last column to tell you there's more characters after, before and after, or before the current position, respectively. The line just scrolls horizontally as necessary. Slay.
Emacs editing mode
Set the emacs option and boom โ interactive input line editing is enabled. ๐ฆ
Warning: This mode is slightly different from the emacs mode in the original Korn shell. Just so you know.
In this mode, various editing commands (typically bound to one or more control characters) cause immediate actions without waiting for a newline. Several editing commands are bound to particular control characters when the shell is invoked, and those bindings can be changed using the bind command. ๐
The following is the list of available editing commands. Each description starts with the name of the command, suffixed with a colon; an [n] (if the command can be prefixed with a count); and any keys the command is bound to by default, written using caret notation โ e.g. the ASCII ESC character is written as ^[. The ^[A-Z] sequences are not case sensitive. A count prefix for a command is entered using the sequence ^[n, where n is a sequence of 1 or more digits. Unless otherwise specified, if a count is omitted, it defaults to 1.
Also, heads up: editing command names are used only with the bind command. Furthermore, many editing commands are useful only on terminals with a visible cursor. The default bindings were chosen to resemble corresponding Emacs key bindings, and the user's tty(4) characters (e.g. ERASE) are bound to reasonable substitutes and override the default bindings. ๐
abort: ^C, ^G
Super useful as a response to a request for a search-history pattern โ it aborts the search. Like hitting the group chat "never mind" button. ๐
auto-insert: [n]
Simply causes the character to appear as literal input. Most ordinary characters are bound to this one.
backward-char: [n] ^B, ^X^D
Moves the cursor backward n characters.
backward-word: [n] ^[b
Moves the cursor backward to the beginning of the word. Words consist of alphanumerics, underscore (_), and dollar sign ($) characters.
beginning-of-history: ^[<
Moves to the beginning of the history. Rewind energy. โญ
beginning-of-line: ^A
Moves the cursor to the beginning of the edited input line.
capitalize-word: [n] ^[C, ^[c
Uppercases the first character in the next n words, leaving the cursor past the end of the last word. Very main character of it.
clear-screen: ^L
Clears the screen if the TERM parameter is set and the terminal supports clearing the screen, then reprints the prompt string and the current input line. Fresh start โจ
comment: ^[#
If the current line doesn't begin with a comment character, one is added at the beginning of the line and the line is entered (as if return had been pressed); otherwise, the existing comment characters are removed and the cursor is placed at the beginning of the line. Toggle-able, we love to see it.
complete: ^[^[
Automatically completes as much as is unique of the command name or the file name containing the cursor. If the entire remaining command or file name is unique, a space is printed after its completion โ unless it's a directory name, in which case / is appended. If there's no command or file name with the current partial word as its prefix, a bell character is output (usually causing a beep to be sounded). ๐ญ
Custom completions may be configured by creating an array named complete_command, optionally suffixed with an argument number to complete only for a single argument. So defining an array named complete_kill provides possible completions for any argument to the kill(1) command, but complete_kill_1 only completes the first argument. For example, this command makes ksh offer a selection of signal names for the first argument to kill(1):
set -A complete_kill_1 -- -9 -HUP -INFO -KILL -TERM
complete-command: ^X^[
Automatically completes as much as is unique of the command name having the partial word up to the cursor as its prefix, as in the complete command above.
complete-file: ^[^X
Automatically completes as much as is unique of the file name having the partial word up to the cursor as its prefix, as in the complete command described above.
complete-list: ^I, ^[=
Completes as much as is possible of the current word, and lists the possible completions for it. If only one completion is possible, matches as in the complete command above.
delete-char-backward: [n] ERASE, ^?, ^H
Deletes n characters before the cursor.
delete-char-forward: [n] Delete
Deletes n characters after the cursor.
delete-word-backward: [n] WERASE, ^[ERASE, ^W, ^[^?, ^[^H, ^[h
Deletes n words before the cursor. So many ways to backspace a whole word, pick your fave ๐
delete-word-forward: [n] ^[d
Deletes n words after the cursor.
down-history: [n] ^N, ^XB
Scrolls the history buffer forward n lines (later). Each input line originally starts just after the last entry in the history buffer, so down-history isn't useful until either search-history or up-history has been performed. Context matters, bestie.
downcase-word: [n] ^[L, ^[l
Lowercases the next n words.
end-of-history: ^[>
Moves to the end of the history.
end-of-line: ^E
Moves the cursor to the end of the input line.
eot: ^_
Acts as an end-of-file. This is useful because edit-mode input disables normal terminal input canonicalization.
eot-or-delete: [n] ^D
Acts as eot if alone on a line; otherwise acts as delete-char-forward. Two jobs, one key ๐ซถ
error:
Error (rings the bell).
exchange-point-and-mark: ^X^X
Places the cursor where the mark is and sets the mark to where the cursor was. Switcheroo ๐
expand-file: ^[*
Appends a * to the current word and replaces the word with the result of performing file globbing on the word. If no files match the pattern, the bell is rung.
forward-char: [n] ^F, ^XC
Moves the cursor forward n characters.
forward-word: [n] ^[f
Moves the cursor forward to the end of the nth word.
goto-history: [n] ^[g
Goes to history number n. Teleport ๐ง
kill-line: KILL
Deletes the entire input line. Gone. Reduced to atoms. ๐
kill-to-eol: [n] ^K
Deletes the input from the cursor to the end of the line if n is not specified; otherwise deletes characters between the cursor and column n.
list: ^[?
Prints a sorted, columnated list of command names or file names (if any) that can complete the partial word containing the cursor. Directory names have / appended to them.
list-command: ^X?
Prints a sorted, columnated list of command names (if any) that can complete the partial word containing the cursor.
list-file: ^X^Y
Prints a sorted, columnated list of file names (if any) that can complete the partial word containing the cursor. File type indicators are appended as described under list above.
newline: ^J, ^M
Causes the current input line to be processed by the shell. The current cursor position may be anywhere on the line โ no need to be at the end, we're not picky.
newline-and-next: ^O
Causes the current input line to be processed by the shell, and the next line from history becomes the current line. This is only useful after an up-history or search-history.
no-op: QUIT
This does nothing. Literally nothing. Iconic. ๐
prev-hist-word: [n] ^[., ^[_`
The last (nth) word of the previous command is inserted at the cursor. Recycling, but make it fashion.
quote: ^^
The following character is taken literally rather than as an editing command.
redraw:
Reprints the prompt string and the current input line.
search-character-backward: [n] ^[^]
Searches backward in the current line for the nth occurrence of the next character typed.
search-character-forward: [n] ^]
Searches forward in the current line for the nth occurrence of the next character typed.
search-history: ^R
Enters incremental search mode. The internal history list is searched backwards for commands matching the input. An initial ^ in the search string anchors the search. The abort key will leave search mode. Other commands will be executed after leaving search mode. Successive search-history commands continue searching backward to the next previous occurrence of the pattern. The history buffer retains only a finite number of lines; the oldest are discarded as necessary. ๐ต๏ธโโ๏ธ
set-mark-command: ^[โจspaceโฉ
Sets the mark at the cursor position.
transpose-chars: ^T
If at the end of line, or if the gmacs option is set, this exchanges the two previous characters; otherwise, it exchanges the previous and current characters and moves the cursor one character to the right.
up-history: [n] ^P, ^XA
Scrolls the history buffer backward n lines (earlier). Time travel, basically โญ
upcase-word: [n] ^[U, ^[u
Uppercases the next n words. LOUD. ๐ข
quote:^Vโ literally the same thing as^^, just a lil alias so it hits different either way ๐yank:^Yโ grabs the most recently killed text string and drops it right at the current cursor position. it's giving copy-paste but make it vintage โจyank-pop:^[yโ okay so immediately after a yank, this swaps the text you just inserted for the next previously killed text string. rotate through your graveyard of deleted text, no cap ๐
The following editing commands lack default bindings but can be used with the bind command:
kill-regionโ deletes the input between the cursor and the mark. bye bestie ๐ซถ
๐ฆ Vi editing mode ๐ฆ
so the vi command-line editor in ksh is basically the same as the vi(1) editor, with these exceptions, and yes u need to know them:
- You start out in insert mode. main character energy from the jump ๐
- There are file name and command completion commands:
=,\,*,^X,^E,^F, and, optionally,โจtabโฉandโจescโฉ. - The
_command is different โ in ksh it's the last argument command; invi(1)it goes to the start of the current line. not me being a different breed ๐ค - The
/andGcommands move in the opposite direction to thejcommand. iconic, slightly unhinged, we respect it - Commands which don't make sense in a single line editor are not available (e.g. screen movement commands and
ex(1)-style colon (:) commands). sorry babe, no screens here ๐
Note that the ^X stands for control-X; also โจescโฉ, โจspaceโฉ, and โจtabโฉ are used for escape, space, and tab, respectively (no kidding).
Like vi(1), there are two modes: โinsertโ mode and โcommandโ mode. In insert mode, most characters are simply put in the buffer at the current cursor position as they are typed; however, some characters are treated specially. In particular, the following characters are taken from current tty(4) settings (see stty(1)) and have their usual meaning (normal values are in parentheses): kill (^U), erase (^?), werase (^W), eof (^D), intr (^C), and quit (^\). bestie those are your tty's settings, she's just borrowing them ๐
In addition to the above, the following characters are also treated specially in insert mode:
^Eโ Command and file name enumeration (see below).^Fโ Command and file name completion (see below). If used twice in a row, the list of possible completions is displayed; if used a third time, the completion is undone. third time's the charm... to undo it ๐ญ^Hโ Erases previous character.^J|^Mโ End of line. The current line is read, parsed, and executed by the shell. go go go ๐ฅ^Lโ Clear the screen (if possible) and redraw the current line. See theclear-screencommand in โEmacs editing modeโ for more information.^Rโ Redraw the current line.^Vโ Literal next. The next character typed is not treated specially (can be used to insert the characters being described here). so meta ๐^Xโ Command and file name expansion (see below).โจescโฉโ Puts the editor in command mode (see below).โจtabโฉโ Optional file name and command completion (see^Fabove), enabled withset -o vi-tabcomplete.
In command mode, each character is interpreted as a command. Characters that don't correspond to commands, are illegal combinations of commands, or are commands that can't be carried out, all cause beeps. yep, she's beeping at you, it's not personal ๐
In the following command descriptions, an [n] indicates the command may be prefixed by a number (e.g. 10l moves right 10 characters); if no number prefix is used, n is assumed to be 1 unless otherwise specified. The term โcurrent positionโ refers to the position between the cursor and the character preceding the cursor. A โwordโ is a sequence of letters, digits, and underscore characters or a sequence of non-letter, non-digit, non-underscore, and non-whitespace characters (e.g. โab2*&^โ contains two words) and a โbig-wordโ is a sequence of non-whitespace characters. there will be a quiz, i'm kidding, but like... ๐
๐ Special ksh vi commands ๐
The following commands are not in, or are different from, the normal vi file editor:
[n]_โ Insert a space followed by the nth big-word from the last command in the history at the current position and enter insert mode; if n is not specified, the last word is inserted.#โ Insert the comment character ('#') at the start of the current line and return the line to the shell (equivalent toI#^J). commenting out ur problems, literally ๐ซถ[n]gโ LikeG, except if n is not specified, it goes to the most recent remembered line.[n]vโ Edit line n using thevi(1)editor; if n is not specified, the current line is edited. The actual command executed isfc -e ${VISUAL:-${EDITOR:-vi}} n.*and^Xโ Command or file name expansion is applied to the current big-word (with an appended'*'if the word contains no file globbing characters) โ the big-word is replaced with the resulting words. If the current big-word is the first on the line or follows one of the characters';','|','&','(', or')', and does not contain a slash ('/'), then command expansion is done; otherwise file name expansion is done. Command expansion will match the big-word against all aliases, functions, and built-in commands as well as any executable files found by searching the directories in thePATHparameter. File name expansion matches the big-word against the files in the current directory. After expansion, the cursor is placed just past the last word and the editor is in insert mode. โจmagicโจ[n]\,[n]^F,[n]โจtabโฉ, and[n]โจescโฉโ Command/file name completion. Replace the current big-word with the longest unique match obtained after performing command and file name expansion.โจtabโฉis only recognized if thevi-tabcompleteoption is set, whileโจescโฉis only recognized if thevi-esccompleteoption is set (seeset -o). If n is specified, the *n*th possible completion is selected (as reported by the command/file name enumeration command).=and^Eโ Command/file name enumeration. List all the commands or files that match the current big-word.@cโ Macro expansion. Execute the commands found in the alias_c.
๐ฆ Intra-line movement commands ๐ฆ
[n]hand[n]^Hโ Move left n characters.[n]land[n]โจspaceโฉโ Move right n characters.0โ Move to column 0.^โ Move to the first non-whitespace character.[n]|โ Move to column n.$โ Move to the last character.[n]bโ Move back n words.[n]Bโ Move back n big-words.[n]eโ Move forward to the end of the word, n times.[n]Eโ Move forward to the end of the big-word, n times.[n]wโ Move forward n words.[n]Wโ Move forward n big-words.%โ Find match. The editor looks forward for the nearest parenthesis, bracket, or brace and then moves the cursor to the matching parenthesis, bracket, or brace. matching ur brackets like it's a personality trait ๐[n]fcโ Move forward to the nth occurrence of the character c.[n]Fcโ Move backward to the nth occurrence of the character c.[n]tcโ Move forward to just before the nth occurrence of the character c.[n]Tcโ Move backward to just before the nth occurrence of the character c.[n];โ Repeats the lastf,F,t, orTcommand.[n],โ Repeats the lastf,F,t, orTcommand, but moves in the opposite direction.
โญ Inter-line movement commands โญ
[n]j,[n]+, and[n]^Nโ Move to the *n*th next line in the history.[n]k,[n]-, and[n]^Pโ Move to the *n*th previous line in the history.[n]Gโ Move to line n in the history; if n is not specified, the number of the first remembered line is used.[n]gโ LikeG, except if n is not specified, it goes to the most recent remembered line.[n]/stringโ Search backward through the history for the nth line containing string; if string starts with'^', the remainder of the string must appear at the start of the history line for it to match.[n]?stringโ Same as/, except it searches forward through the history.[n]nโ Search for the *n*th occurrence of the last search string; the direction of the search is the same as the last search.[n]Nโ Search for the *n*th occurrence of the last search string; the direction of the search is the opposite of the last search.
๐ Edit commands ๐
[n]aโ Append text n times; goes into insert mode just after the current position. The append is only replicated if command mode is re-entered i.e.โจescโฉis used.[n]Aโ Same asa, except it appends at the end of the line.[n]iโ Insert text n times; goes into insert mode at the current position. The insertion is only replicated if command mode is re-entered i.e.โจescโฉis used.[n]Iโ Same asi, except the insertion is done just before the first non-blank character.[n]sโ Substitute the next n characters (i.e. delete the characters and go into insert mode).Sโ Substitute whole line. All characters from the first non-blank character to the end of the line are deleted and insert mode is entered.[n]cmove-cmdโ Change from the current position to the position resulting from nmove-cmds (i.e. delete the indicated region and go into insert mode); ifmove-cmdisc, the line starting from the first non-blank character is changed.Cโ Change from the current position to the end of the line (i.e. delete to the end of the line and go into insert mode).[n]xโ Delete the next n characters.[n]Xโ Delete the previous n characters.Dโ Delete to the end of the line.[n]dmove-cmdโ Delete from the current position to the position resulting from nmove-cmds;move-cmdis a movement command (see above) ord, in which case the current line is deleted.[n]rcโ Replace the next n characters with the character c.[n]Rโ Replace. Enter insert mode but overwrite existing characters instead of inserting before existing characters. The replacement is repeated n times.[n]~โ Change the case of the next n characters. case flip era ๐ฅ[n]ymove-cmdโ Yank from the current position to the position resulting from nmove-cmds into the yank buffer; ifmove-cmdisy, the whole line is yanked.Yโ Yank from the current position to the end of the line.[n]pโ Paste the contents of the yank buffer just after the current position, n times.[n]Pโ Same asp, except the buffer is pasted at the current position.
Miscellaneous vi commands
^Jand^Mโ bestie this is just โจsendโจ: the current line gets read, parsed, and executed by the shell. That's it, that's the post. ๐^Lโ clears the screen (if it can, lowkey not always possible) and redraws the current line so it looks cute again ๐^Rโ just redraws the current line. same energy, no screen wipe ๐ธ[n].โ redo the last edit command n times. yes, n. do it again, and again, and again ๐ฅuโ undo the last edit command. the "not me" of keybindings ๐Uโ undo all the changes you've made to the current line. full factory reset, we're starting over ๐intrandquitโ the interrupt and quit terminal characters cause the current line to be deleted and a brand new prompt to be printed. clean slate, main character energy ๐
๐๏ธ FILES
~/.profileโ your login profile. very much your personal vibe file ๐/etc/ksh.kshrcโ the global configuration file. not sourced by default, so don't come for it ๐ซถ/etc/profileโ the system login profile./etc/shellsโ the shell database./etc/suid_profileโ the privileged shell profile. fancy ๐
๐ SEE ALSO
csh(1), ed(1), mg(1), sh(1), stty(1), vi(1), shells(5), environ(7), script(7)
S. R. Bourne, โThe UNIX Shellโ, Bell System Technical Journal, 57:6, pp. 1971-1990, 1978.
S. R. Bourne, An Introduction to the UNIX Shell, AT&T Bell Laboratories, Computing Science Technical Report, 70, 1978.
Morris Bolsky and David Korn, The KornShell Command and Programming Language, Prentice Hall, First Edition 1989, ISBN 0135169720.
Stephen G. Kochan and Patrick H. Wood, UNIX Shell Programming, 3rd Edition, Sams, 2003, ISBN 0672324903.
IEEE Inc., IEEE Standard for Information Technology - Portable Operating System Interface (POSIX) - Part 2: Shell and Utilities, 1993, ISBN 1-55937-255-9.
๐ท๏ธ VERSION
This page documents version @(#)PD KSH v5.2.14 99/07/13.2 of the public domain Korn shell. vintage but iconic, iykyk โญ
๐ AUTHORS
This shell is based on the public domain 7th edition Bourne shell clone by Charles Forsyth and parts of the BRL shell by Doug A. Gwyn, Doug Kingston, Ron Natalie, Arnold Robbins, Lou Salkind, and others. The first release of pdksh was created by Eric Gisin, and it was subsequently maintained by John R. MacMillan change!john@sq.sq.com, Simon J. Gerraty sjg@zen.void.oz.au, and Michael Rendell michael@cs.mun.ca. The CONTRIBUTORS file in the source distribution contains a more complete list of people and their part in the shell's development. everybody say thank you ๐ซถ๐
๐ BUGS
okay so listen up bestie, this one's real:
$(command) expressions are currently parsed by finding the closest matching (unquoted) parenthesis. so constructs inside $(command) may produce an error ๐ญ for example, the parenthesis in x);; is interpreted as the closing parenthesis in $(case x in x);; *);; esac).
like, it's not being mean, it genuinely thinks that's the end of the thing. no cap. don't fight it, just work around it ๐
and that's the whole page, you made it to the end, I'm so proud of you ๐โจ this lil doc drop is from Debian, dated December 31, 2025 โ go forth and shell, bestie, the terminal is yours ๐ ๐ท๐ฆ
๐ฆ where this page comes from
- nixpkgs unstable: loksh 7.9
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms