ksh - Unix, Linux Command (2023)

ksh - Unix, Linux Command (3)

sh, rsh, pfsh - shell, the standard/restricted command and programming language

ksh, rksh, pfksh - KornShell, a standard/restricted command and programming language

ksh93, rksh93, pfksh93 - KornShell, a standard/restricted command and programming language




[±abcefhiknoprstuvxBCDP ] [-R file ] [±o option ] ... [- ] [ arg ... ]

is a command and programming languagethat executes commands read from a terminalor a file.

is a restricted version of the

command interpreter

it is used to set up login names and execution environments whosecapabilities are more controlled than those of the standard shell.

is a profile shell version of the

command interpreter

it is used to to execute commands with the attributes specified bythe user’s profiles (seepfexec(1)).SeeInvocation belowfor the meaning of arguments to the shell.

NOTE: Pfksh, Rpfksh and pfexec parts are not related to Linux systems. Rksh can be used as rksh symlink to ksh93 or as ksh -r.


Ametacharacter is one of the following characters:

; & ( ) | < > new-line space tab

Ablank is atab or aspace. Anidentifier is a sequence of letters, digits, or underscoresstarting with a letter or underscore.Identifiers are used as components ofvariable names.Avname is a sequence of one or more identifiersseparated by a . and optionally precededby a ..Vnames are used as function and variable names.Aword is a sequence ofcharacters from the character set defined by the current locale,excluding non-quotedmetacharacters.

Acommand is a sequence of characters in the syntaxof the shell language.The shell reads each command andcarries out the desired action either directly or by invokingseparate utilities.A built-in command is a command that is carried out by theshell itself without creating a separate process.Some commands are built-in purely for convenienceand are not documented here.Built-ins that causeside effects in the shell environment andbuilt-ins that are found before performing apath search (seeExecution below)are documented here.For historical reasons, some ofthese built-ins behave differently thanother built-ins and are calledspecial built-ins.


Asimple-command is a list of variable assignments(seeVariable Assignments below)or a sequence ofblank separated wordswhich may be preceded by a list of variable assignments(seeEnvironment below).The first word specifies the name of the command tobe executed.Except as specified below,the remaining words are passed as argumentsto the invoked command.The command name is passed as argument 0(seeexec(2)).Thevalue of a simple-command is its exit status; 0-255if it terminates normally; 256+signum ifit terminates abnormally (the name of the signal correspondingto the exit status can beobtained via the-l option of thekill built-in utility).

Apipeline is a sequence of one or morecommands separated by|. The standard output of each command but the lastis connected by apipe(2)to the standard input of the next command.Each command,except possibly the last,is run as a separate process;the shell waits for the last command to terminate.The exit status of a pipeline is the exitstatus of the last command unless thepipefail option is enabled.Each pipeline can be preceded by thereserved word ! which causes the exit status of the pipeline to become0 if the exit status of the last command is non-zero, and1 if the exit status of the last command is 0.

Alist is a sequence of one or morepipelinesseparated by;, &, |&, &&, or||, and optionally terminated by;, &, or|&. Of these five symbols,;, &, and|& have equal precedence,which is lower than that of&& and||. The symbols&& and|| also have equal precedence.A semicolon(;) causes sequential execution of the preceding pipeline; an ampersand(&) causes asynchronous execution of the preceding pipeline (i.e., the shell doesnot wait for that pipeline to finish).The symbol|& causes asynchronous execution of the preceding pipelinewith a two-way pipe established to the parent shell;the standard input and output of the spawned pipelinecan be written to and read from by the parent shellby applyingthe redirection operators<& and>& with argp to commands and by using-p option ofthe built-in commandsread andprint described later.The symbol&& (||) causes thelist following it to be executed only if the precedingpipelinereturns a zero (non-zero) value.One or more new-lines may appear in alist instead of a semicolon,to delimit a command.The firstitem of the firstpipeline of alist that is a simple command not beginningwith a redirection, and not occurring within awhile, until, orif list, can be preceded by a semicolon.This semicolonis ignored unless theshowme option is enabled as described withtheset built-in below.

Acommand is either a simple-commandor one of the following.Unless otherwise stated,the value returned by a command is that of thelast simple-command executed in the command.

for vname [ in word ... ] ;do list ;done
Each time afor command is executed,vname is set to the nextword taken from thein word list.Ifin word ...is omitted, thenthefor command executes the do list once for each positional parameterthat is set starting from1 (seeParameter Expansion below).Execution ends when there are no more words in the list.
for (( [expr1] ; [expr2] ; [expr3] )) ;do list ;done
The arithmetic expressionexpr1 is evaluated first(seeArithmetic evaluation below).The arithmetic expressionexpr2 is repeatedly evaluated until it evaluates to zero and when non-zero,list is executed and the arithmetic expressionexpr3 evaluated.If any expressionis omitted, then it behaves as if it evaluated to 1.
select vname [ in word ... ] ;do list ;done
Aselect command prints on standard error (file descriptor 2) the set ofwords, each preceded by a number.Ifin word ...is omitted, thenthepositional parameters starting from1 are used instead(seeParameter Expansion below).The PS3 prompt is printedand a line is read from the standard input.If this line consists of the numberof one of the listedwords, then the value of the variablevname is set to theword corresponding to this number.If this line is empty, the selection list isprinted again.Otherwise the value of the variablevname is set tonull. The contents of the line read from standard input issaved inthe variable REPLY. Thelist is executed for each selection until abreak orend-of-file is encountered.If the REPLY variable is set tonull by the execution oflist, then the selection list is printed beforedisplaying the PS3 prompt for the next selection.
case word in [ [(]pattern [ | pattern ] ... ) list ;; ] ... esac
Acase command executes thelist associated with the firstpattern that matchesword. The form of the patterns isthe same as that used forfile-name generation (seeFile Name Generation below).The;; operator causes execution ofcase to terminate.If;& is used in place of;; the next subsequent list, if any, is executed.
if list ;then list [
;elif list ;then list ] ... [ ;else list ] ;fiThelist following if is executed and,if itreturns a zero exit status, thelist followingthe firstthen is executed.Otherwise, thelist following elifis executed and, if its value is zero,thelist followingthe nextthen is executed.Failing each successiveelif list, theelse list is executed.If theif list has non-zero exit statusand there is noelse list, then theif command returns a zero exit status.
while list ;do list ;done
until list ;do list ;done
Awhile command repeatedly executes thewhile list and, if the exit status of the last command in the list is zero, executesthedo list; otherwise the loop terminates.If no commands in thedo list are executed, then thewhile command returns a zero exit status;until may be used in place ofwhile to negatethe loop termination test.
Theexpression is evaluated using the rules for arithmetic evaluation described below.If the value of the arithmetic expression is non-zero, the exitstatus is 0, otherwise the exit status is 1.
Executelist in a separate environment.Note, that if two adjacent open parentheses areneeded for nesting, a space must be inserted to avoidevaluation as an arithmetic command as described above.
{ list;}
list is simply executed.Note that unlike the metacharacters( and), { and} arereserved words and must occurat the beginning of a line or after a; in order to be recognized.
[[ expression ]]
Evaluatesexpression and returns a zero exit status whenexpression is true.SeeConditional Expressions below, for a description ofexpression.
function varname { list ;}
varname () { list ;}
Define a function which is referenced byvarname. A function whosevarname contains a. is called a discipline function and the portionof thevarname preceding the last. must refer to an existing variable.The body of the function is thelist of commands between{ and}. A function defined with the function varnamesyntax can also be used as an argument to the .special built-in command to get the equivalent behavioras if the varname() syntax were used to define it.(SeeFunctions below.)
time [ pipeline ]
If pipeline is omitted the user and system time forthe current shell and completed child processes is printedon standard error.Otherwise,pipeline is executed and the elapsed time as well asthe user and system time are printed on standard error.The TIMEFORMAT variable may be set to a format string that specifies how the timinginformation should be displayed.SeeShell Variables belowfor a description of the TIMEFORMAT variable.

The following reserved wordsare recognized as reserved only when they are the first word of a commandand are not quoted:

if then else elif fi case esac for while until do done { } function select time [[ ]] !

Variable Assignments.

One or more variable assignments can start a simple commandor can be arguments to thetypeset, enum, export, orreadonly special built-in commands as well asto other declaration commands created as types.The syntax for an assignment is of the form:

No space is permitted between varname and the = orbetween = and word.
No space is permitted between varname and the =.An assign_list can be one of the following:
word ...
Indexed array assignment.
[word]=word ...
Associative array assignment.If preceded bytypeset -a this will create an indexed array instead.
assignment ...
Compound variable assignment.This creates a compound variable varname withsub-variables of the form varname.name,where name is the name portion of assignment.The value of varname will contain all the assignment elements.Additional assignments made to sub-variables of varnamewill also be displayed as part of the value of varname.If no assignments are specified, varname will bea compound variable allowing subsequence child elements to be defined.
typeset [options] assignment ...
Nested variable assignment. Multiple assignmentscan be specified by separating each of them with a ;.The previous value is unset before the assignment.Other declaration commands such asreadonly, enum, andother declaration commands can be used in place oftypeset.
. filename
Include the assignment commands contained infilename.

In addition, a += can be used in place of the =to signify adding to or appending to the previous value.When += is applied to an arithmetic type, wordis evaluated as an arithmetic expression and added to the current value.When applied to a string variable, the value defined by wordis appended to the value. For compound assignments, the previousvalue is not unset and the new values are appended to thecurrent ones provided that the types are compatible.

The right hand side of a variable assignment undergoes all the expansionlist below except word splitting, brace expansion, and file name generation.When the left hand side is an assignment is a compound variable andthe right hand is the name of a compound variable, the compound variableon the right will be copied or appended to the compound variable on the left.


A word beginning with# causes that word and all the following characters up to a new-lineto be ignored.


The first word of each command is replaced by the text of analias if analias for this word has been defined.Analias name consists of any number of characters excluding metacharacters,quoting characters,file expansion characters,parameter expansion and command substitutioncharacters,and=. The replacement string can contain anyvalid shell scriptincluding the metacharacters listed above.The first word of each command in thereplaced text,other thanany that are in the process of being replaced,will be tested for aliases.If the last character of the alias value is ablank then the word following the alias will also be checked for aliassubstitution.Aliases can be used to redefinebuilt-in commands but cannot be used to redefinethe reserved words listed above.Aliases can be created and listed with thealias command and can be removed with theunalias command.

Aliasing is performed whenscripts are read,not while they are executed.Therefore,for an alias to take effect,the aliasdefinition command has to be executed beforethe command which references the alias is read.

The following aliasesare compiled into the shellbut can be unset or redefined:

autoload='typeset -fu'
command='command '
compound='typeset -C'
float='typeset -lE'
functions='typeset -f'
hash='alias -t --'
history='hist -l'
integer='typeset -li'
nameref='typeset -n'
nohup='nohup '
r='hist -s'
redirect='command exec'
source='command .'
stop='kill -s STOP'
suspend='kill -s STOP $$'
times='{ { time;} 2>&1;}'
type='whence -v'

Tilde Substitution.

After alias substitution is performed, each wordis checked to see if it begins with an unquoted~. For tilde substitution,word also refers to theword portion of parameter expansion(seeParameter Expansion below).If it does, then the word up to a/ is checked to see if it matches a user name in thepassword database (Seegetpwname(3).)If a match is found, the~ and the matched login name are replaced by thelogin directory of the matched user.If no match is found, the original text is left unchanged.A~ by itself, or in front of a/, is replaced by $HOME. A~ followed by a+ or- is replaced by the value of $PWD and $OLDPWD respectively.

In addition,when expanding avariable assignment, tilde substitution is attempted whenthe value of the assignmentbegins with a~, and when a~ appears after a:. The: also terminates a~ login name.

Command Substitution.

The standard output from a command list enclosed inparentheses preceded by a dollar sign ($(list)),or in a brace group preceded by a dollar sign (${ list;}), or in a pair of grave accents (``)may be used as part or allof a word;trailing new-lines are removed.In the second case, the { and } are treated as a reserved wordsso that { must be followed by a blank and } mustappear at the beginning of the line or follow a ;.In the third (obsolete) form, the string between the quotes is processedfor special quoting characters before the command is executed (seeQuoting below).The command substitution$(cat file)can be replaced by the equivalent but faster$(<file).The command substitution$(n<#)will expand to the current byte offset for file descriptorn. Except for the second form, the command list is run in a subshell so that noside effects are possible.For the second form, the final} will be recognized as a reserved word after any token.

Arithmetic Substitution.

An arithmetic expression enclosed in doubleparentheses preceded by a dollar sign ($(()) )is replaced by the value of the arithmetic expressionwithin the double parentheses.

(Video) How to switch from Bash to Korn Shell on Linux

Process Substitution.

This feature is only available onversions of the UNIX operating system that support the/dev/fd directory for naming open files.Each command argument of the form<(list)or>(list)will run processlist asynchronously connected to some file in/dev/fd. The name of this file will become the argument to the command.If the form with> is selected then writing on this file will provide input forlist. If< is used,then the file passed as an argument will contain the output of thelist process.For example,

paste <(cut -f1 file1) <(cut -f3 file2) | tee >(process1) >(process2)

cuts fields 1 and 3 fromthe filesfile1 andfile2 respectively,pastes the results together, andsends itto the processesprocess1 andprocess2, as well as putting it onto the standard output.Note that the file, which is passed as an argument to the command,is a UNIXpipe(2)so programs that expect tolseek(2)on the file will not work.

Process substitution of the form<(list)can also be used with the< redirection operator which causes the output oflist to be standard input or the input for whatever file descriptor is specified.

Parameter Expansion.

Aparameter is avariable, one or more digits,or any of the characters*, @, #, ?, -, $, and!\^. Avariable is denoted by a vname.To create a variable whosevname contains a .,a variable whosevname consists of everything before the last . must already exist.Avariable has avalue and zero or moreattributes. Variables can be assignedvalues andattributes by using thetypeset special built-in command.The attributes supported by the shell are describedlater with thetypeset special built-in command.Exported variables pass values and attributes tothe environment.

The shell supports both indexed and associative arrays.An element of an array variable is referenced by asubscript. Asubscript for an indexed array is denoted byanarithmetic expression (seeArithmetic evaluation below)between a[ and a]. To assign values to an indexed array, usevname=(value ...) orset -A vname value ... .The value of all non-negativesubscripts must be in therange of0 through 4,194,303.A negative subscript is treated as an offset from the maximumcurrent index +1 so that -1 refers to the last element.Indexed arrays can be declared with the-a option totypeset. Indexed arrays need not be declared.Any reference to a variablewith a valid subscript islegal and an array will be created if necessary.

An associative array is created with the-A option totypeset. Asubscript for an associative array is denoted bya string enclosed between[ and].

Referencing any array without a subscriptis equivalent to referencing the array with subscript 0.

Thevalue of avariable may be assigned by writing:

vname=value [vname=value ] ...


vname[subscript]=value [vname[subscript]=value ] ...

Note that no space is allowed before or after the=.

Anameref is a variable that is a reference to another variable.A nameref is created with the-n attribute oftypeset. The value of the variable at the time of thetypeset command becomes the variable that will be referenced wheneverthe nameref variable is used.The name of a nameref cannot contain a ..When a variable or function name contains a ., and the portionof the name up to the first . matches thename of a nameref, the variable referred to is obtained byreplacing the nameref portion with the name of the variablereferenced by the nameref.If a nameref is used as the index of a for loop,a name reference is established for each item in the list.A nameref provides a convenient way to refer to the variableinside a function whose name is passed as an argument to a function.For example, if the name of a variable is passed as the firstargument to a function, the command

typeset -n var=$1

inside the function causes references and assignments tovar to be references and assignments to the variable whosename has been passed to the function.

If any of the floating point attributes,-E, -F, or-X, or the integer attribute,-i, is set forvname, then thevalue is subject to arithmetic evaluation as described below.

Positional parameters,parameters denoted by a number,may be assigned values with theset special built-in command.Parameter$0 is set from argument zero when the shellis invoked.

The character$ is used to introduce substitutableparameters.

The shellreads all the characters from${ to the matching} as part of the same word even if it containsbraces or metacharacters.The value, if any, of the parameter is substituted.The braces are required whenparameter is followed by a letter, digit, or underscorethat is not to be interpreted as part of its name,when the variable name contains a ..The braces are also required when a variable is subscriptedunless it is part of an Arithmetic Expressionor a Conditional Expression.Ifparameter is one or more digits then it is a positional parameter.A positional parameter of more than one digit must beenclosed in braces.Ifparameter is* or@, then all the positionalparameters, starting with$1, are substituted(separated by a field separator character).If an arrayvname with subscript* @, or of the formsub1 .. sub2. is used,then the valuefor each of theelements betweensub1 andsub2 inclusive (or all elements for* and@) is substituted,separated bythe first character ofthe value of IFS.
Ifparameter is* or@, the number of positional parameters is substituted.Otherwise, the length of the value of theparameter is substituted.
The number of elements in the arrayvname is substituted.
Expands to the type name (SeeType Variables below) or attributes of the variable referred to byvname.
Expands to the name of the variable referred to byvname. This will bevname except whenvname is a name reference.
Expands to name of the subscript unlesssubscript is*, @. or of the formsub1 .. sub2. Whensubscript is*, the list of array subscripts for vnameis generated.For a variable that is not an array, the value is 0 if the variableis set. Otherwise it is null.Whensubscript is@, same as above, except that when used in double quotes,each array subscript yields a separateargument.Whensubscript is of the formsub1 .. sub2 it expandsto the list of subscripts betweensub1 andsub2 inclusive using the same quoting rules as@.
Expands to the names of the variables whose names begin withprefix.
Ifparameter is set and is non-null then substitute its value;otherwise substituteword.
Ifparameter is not set or is null then set it toword; the value of the parameter is then substituted.Positional parameters may not be assigned toin this way.
Ifparameter is set and is non-null then substitute its value;otherwise, printword and exit from the shell (if not interactive).Ifword is omitted then a standard message is printed.
Ifparameter is set and is non-null then substituteword; otherwise substitute nothing.
In the above,word is not evaluated unless it isto be used as the substituted string,so that, in the following example,pwd is executed only ifd is not set or is null:
print ${d:-$(pwd)}
If the colon (: ) is omitted from the above expressions,then the shell only checks whetherparameter is set or not.
Expands to the portion of the value ofparameter starting at the character (counting from0) determined by expandingoffset as an arithmetic expression and consisting of thenumber of characters determined by the arithmetic expressiondefined bylength. In the second form, the remainder of the value is used.IfA negativeoffset counts backwards from the end ofparameter. Note that one or moreblanks is required in front of a minus signto prevent the shell from interpreting the operator as:-. Ifparameter is* or@, or is an array name indexed by* or@, thenoffset andlength refer to the array index and numberof elements respectively.A negativeoffset is taken relative to one greater than the highest subscriptfor indexed arrays.The order for associate arrays is unspecified.
Ifthe shellpattern matches the beginning of the value ofparameter, then the value ofthis expansion is the value of theparameter with the matched portion deleted;otherwise the value of thisparameter is substituted.In the first form the smallest matching pattern is deleted and in thesecond form the largest matching pattern is deleted.Whenparameter is@, *, or an array variable with subscript@ or*, the substring operation is applied to each element in turn.
Ifthe shellpattern matches the end of the value ofparameter, then the value ofthis expansion is the value of theparameter with the matched part deleted;otherwise substitute the value ofparameter. In the first form the smallest matching pattern is deleted and in thesecond form the largest matching pattern is deleted.Whenparameter is@, *, or an array variable with subscript@ or*, the substring operation is applied to each element in turn.
Expandsparameter and replaces the longest match ofpattern with the givenstring. Each occurrence of \n instring is replaced by the portion of parameterthat matches the n-th sub-pattern.In the first form,only the first occurrence ofpattern is replaced.In the second form,each match forpattern is replaced by the givenstring. The third form restricts the pattern match to the beginning of the stringwhile the fourth form restricts the pattern match to the end ofthe string.Whenstring is null, thepattern will be deleted and the/ in front ofstring may be omitted.Whenparameter is@, *, or an array variable with subscript@ or*, the substitution operation is applied to each element in turn.In this case, thestring portion ofword will be re-evaluated for each element.
The followingparametersare automatically set by the shell:
# The number of positional parameters in decimal.
- Options supplied to the shell on invocation or bytheset command.
? The decimal value returned by the last executed command.
$ The process number of this shell.
_ Initially, the value of_ is an absolute pathname of the shell or script being executedas passed in theenvironment. Subsequently it is assigned the last argument of the previous command.This parameter is not set for commands which are asynchronous.This parameter is also used to hold the name of the matching MAIL file when checking for mail.While defining a compound variable or a type,_ is initialized as a reference to the compound variable or type.When a discipline function is invoked,_ is initialized as a reference to the variable associated withthe call to this function.Finally when_ is used as the name of the first variable of a type definition,the new type is derived from the type of the first variable (SeeType Variables below.).
! The process number of the last background command invoked orthe most recent job put in the background with thebg built-in command.
When processing a DEBUG trap, this variable contains the current command linethat is about to run.
This variable contains the value of the keyboard character(or sequence of characters if the first character is an ESC, ascii033) that hasbeen entered when processing a KEYBD trap(seeKey Bindings below).If the value is changed as part of the trap action, then the newvalue replaces the key (or key sequence) that caused the trap.
The character position of the cursor at the time of the most recent KEYBD trap.
The value is set to ESC when processing a KEYBD trap while invi insert mode. (SeeVi Editing Mode below.)Otherwise,.sh.edmode is null when processing a KEYBD trap.
The characters in the input buffer at the time of the most recent KEYBD trap.The value is null when not processing a KEYBD trap.
The pathname of the file than contains the current command.
.sh.fun The name of the current function that is being executed.
Set to the current function depth. This can be changedinside a DEBUG trap and will set the context to the specifiedlevel.
Set during a DEBUG trap to the line number for the caller ofeach function.
An indexed array which stores the most recent match and sub-patternmatches after conditional pattern matches that match and aftervariables expansions using the operators#, %, or/. The0-th element stores the complete match and thei-th. element stores thei-th submatch.The.sh.match variablebecomes unset when the variable that has expandedis assigned a new value.
Set to the name of the variable at the time that adiscipline function is invoked.
Set to the name subscript of the variable at the time that adiscipline function is invoked.
The current depth for subshells and command substitution.
Set to the value of the variable at the time that theset orappend discipline function is invoked.
Set to a value that identifies the version of this shell.
KSH_VERSION A name reference to.sh.version.
LINENO The current line number within the script orfunction being executed.
OLDPWD The previous working directory set by thecd command.
OPTARG The value of the last option argument processed by thegetopts built-in command.
OPTIND The index of the last option argument processed by thegetopts built-in command.
PPID The process number of the parent of the shell.
PWD The present working directory set by thecd command.
RANDOM Each time this variable is referenced, a random integer,uniformly distributed between 0 and 32767, is generated.The sequence of random numbers can be initialized by assigninga numeric value to RANDOM.
REPLY This variable is set by theselect statement and bytheread built-in command when no arguments are supplied.
SECONDS Each time this variable is referenced, the number ofseconds since shell invocation is returned.If this variable isassigned a value, then the value returned upon reference willbe the value that was assigned plus the number of seconds since the assignment.
SHLVL An integer variable the is incremented each time the shellis invoked and is exported.If SHLVL is not in the environment when the shell is invoked, it is setto 1.
The followingvariablesare used by the shell:
CDPATH The search path for thecd command.
COLUMNS If this variable is set,the value is used to define the width of the edit windowfor the shell edit modes and for printingselect lists.
EDITOR If the VISUAL variable is not set,the value of this variable will be checked for the patternsas described with VISUAL below and the corresponding editing option(see Special Commandset below)will be turned on.
ENV If this variable is set, thenparameter expansion, command substitution, and arithmetic substitutionare performed onthe value to generatethe pathname of the script that will beexecuted when the shellis invoked interactively(seeInvocation below).This file is typically used foralias andfunction definitions.The default value is $HOME/.kshrc.On systems that support a system wide /etc/ksh.kshrc initialization file,if the filename generated by the expansion of ENV begins with/./ or././ the system wide initialization file will not be executed.
FCEDIT Obsolete name forthe default editor name for thehist command. FCEDIT is not used when HISTEDIT is set.
FIGNORE A pattern that defines the set of filenames that will beignored when performing filename matching.
FPATH The search path for function definitions.The directories in this path are searched for a file with the same nameas the function or command when a function with the-u attribute is referenced and when a command is not found.If an executable file with the name of that command is found,then it is read and executedin the current environment.Unlike PATH, the current directory must be representedexplicitly by. rather than by adjacent: characters or a beginning or ending:.
HISTCMD Number of the current command in the history file.
HISTEDIT Name forthe default editor name for thehist command.
HISTFILE If this variable is set when the shell is invoked, thenthe value is the pathname of the file that will beused to store the command history (seeCommand Re-entry below).
HISTSIZE If this variable is set when the shell is invoked, thenthe number of previously entered commands thatare accessible by this shellwill be greater than or equal to this number.The default is 512.
HOME The default argument (home directory) for thecd command.
IFS Internal field separators,normallyspace, tab, andnew-line that are used to separate the results ofcommand substitution or parameter expansionand to separate fields with the built-in commandread. The first character of the IFS variable is used to separate arguments for the "$*"substitution (seeQuoting below).Each single occurrence ofan IFS character in the string to be split,that is not in the isspace character class, and anyadjacent characters in IFS that are in the isspace character class, delimit a field.One or morecharacters in IFS that belong to the isspace character class,delimit a field.In addition, if the same isspace character appearsconsecutively inside IFS, this character is treated as if it were not in the isspaceclass, so that if IFS consists of twotab characters,then two adjacenttab characters delimit a null field.
JOBMAX This variable defines the maximum number running background jobsthat can run at a time. When this limit is reached, theshell will wait for a job to complete before staring a new job.
LANG This variable determines the locale category for anycategory not specifically selected with a variablestarting with LC_ or LANG.
LC_ALL This variable overrides the value of the LANG variable and any other LC_ variable.
LC_COLLATE This variable determines the locale category for charactercollation information.
LC_CTYPE This variable determines the locale category for characterhandling functions.It determines the character classes for pattern matching (seeFile Name Generation below).
LC_NUMERIC This variable determines the locale category for thedecimal point character.
LINES If this variable is set,the value is used to determine the column length for printingselect lists.Select lists will print vertically until about two-thirds of LINES lines are filled.
MAIL If this variable is set to the name of a mail fileand the MAILPATH variable is not set,then the shell informs the user of arrival of mailin the specified file.
MAILCHECK This variable specifies how often (in seconds) theshell will check for changes in the modification timeof any of the files specified by the MAILPATH or MAIL variables.The default value is 600 seconds.When the time has elapsedthe shell will check before issuing the next prompt.
MAILPATH A colon (: )separated list of file names.If this variable is set,then the shell informs the user ofany modifications to the specified filesthat have occurred within the last MAILCHECK seconds.Each file name can be followed by a? and a message that will be printed.The message will undergo parameter expansion, command substitution,and arithmetic substitutionwith the variable$_ defined as the name of the file that has changed.The default message isyou have mail in $_.
PATH The search path for commands (seeExecution below).The user may not changePATH if executing under(except in.profile).
PS1 The value of this variable is expanded for parameterexpansion, command substitution, and arithmetic substitution to define theprimary prompt string which by default is‘‘$’’. The character! in the primary prompt string is replaced by thecommand number (seeCommand Re-entry below).Two successive occurrences of! will produce a single! when the prompt string is printed.
PS2 Secondary prompt string, by default‘‘> ’’.
PS3 Selection prompt stringused within aselect loop, by default‘‘#? ’’.
PS4 The value of this variable is expanded for parameter evaluation,command substitution, and arithmetic substitutionand precedes each line of an execution trace.By default, PS4 is‘‘+ ’’. In additionwhen PS4 is unset,the execution trace prompt is also‘‘+ ’’.
SHELL The pathname of theshell is kept in the environment.At invocation, if the basename of this variable isrsh, rksh, orkrsh, then the shell becomes restricted.If it ispfsh orpfksh, then the shell becomes a profile shell (seepfexec(1)).
TIMEFORMAT The value of this parameter is used as a format string specifyinghow the timing information for pipelines prefixed with thetime reserved word should be displayed.The % character introduces a format sequence that isexpanded to a time value or other information.The format sequences and their meanings are as follows.
%% A literal %.
%[p][l]R The elapsed time in seconds.
%[p][l]U The number of CPU seconds spent in user mode.
%[p][l]S The number of CPU seconds spent in system mode.
%P The CPU percentage, computed as (U + S) / R.
The brackets denote optional portions.The optional p is a digit specifying the precision,the number of fractional digits after a decimal point.A value of 0 causes no decimal point or fraction to be output.At most three places after the decimal point can be displayed;values of p greater than 3 are treated as 3.If p is not specified, the value 3 is used.
The optional l specifies a longer format, includinghours if greater than zero,minutes, and seconds of the form HHhMMmSS.FFs.The value of p determines whether or not the fraction isincluded.
All other characters are output without change and a trailingnewline is added.If unset, the default value, $’\nreal\t%2lR\nuser\t%2lU\nsys%2lS’,is used. If the value is null, no timing information is displayed.
TMOUT If set to a value greater than zero, TMOUT will be the default timeout value for theread built-in command.Theselect compound command terminates after TMOUT seconds when input is from a terminal.Otherwise,the shell will terminate if a line is not entered withinthe prescribed number of seconds while reading from a terminal.(Note that the shell can be compiled with a maximum boundfor this value which cannot be exceeded.)
VISUAL If the value of this variable matches the pattern*[Vv][Ii]*, then thevi option(see Special Commandset below)is turned on.If the value matches the pattern*gmacs* , thegmacs option is turned on.If the value matches the pattern*macs*, then theemacs optionwill be turned on.The value of VISUAL overrides the value of EDITOR.

The shell gives default values toPATH, PS1, PS2,PS3, PS4, MAILCHECK, FCEDIT,TMOUT and IFS,while HOME, SHELL, ENV, and MAIL arenot set at all by the shell (although HOME is set bylogin(1)).On some systems MAIL and SHELL are alsoset bylogin(1).

Field Splitting.

After parameter expansion and command substitution,the results of substitutions are scanned for the field separatorcharacters (those found in IFS )and split into distinct fields where such characters are found.Explicit null fields ("" or '') are retained.Implicit null fields(those resulting fromparameters that have no values or command substitutions with no output) are removed.

If thebraceexpand (-B) option is set then each of the fields resulting from IFS are checked to see if they contain one or more of the brace patterns{*,*}, {l1..l2} ,{n1..n2} ,{n1..n2% fmt} ,{n1..n2 ..n3} , or{n1..n2 ..n3%fmt} , where* represents any character,l1,l2 are letters andn1,n2,n3 are signed numbers andfmt is a format specified as used byprintf. In each case, fields are createdby prepending the characters before the{ and appending the characters after the} to each of the strings generated by the characters betweenthe{ and}. The resulting fields are checked to see if they have anybrace patterns.

In the first form, a field is created for each string between{ and,, between, and,, and between, and}. The string represented by* can contain embedded matching{ and} without quoting.Otherwise, each{ and} with* must be quoted.

In the seconds form,l1 andl2 must both be either upper case or both be lower case charactersin the C locale. In this case a field is created for each characterfroml1 thrul2.

In the remaining forms, a field is created for each number starting atn1 and continuing until it reachesn2 incrementingn1 byn3. The cases wheren3 is not specified behave as ifn3 where1 ifn1<=n2 and-1 otherwise.If forms which specify%fmt any format flags, widths and precisions can be specifiedandfmt can end in any of the specifierscdiouxX. For example,{a,z}{1..5..3%02d}{b..c}x expands to the 8 fields,a01bx, a01cx, a04bx, a04cx, z01bx, z01cx, z04bx andz4cx.

File Name Generation.

Following splitting, each field is scanned for the characters*, ?, (, and[ unless the-f option has been set.If one of these characters appears,then the word is regarded as apattern. Each file name component that contains any pattern characteris replaced with a lexicographically sorted set of namesthat matches the patternfromthat directory.If no file name is found that matches the pattern, thenthat component of the filename is left unchanged unlessthe pattern is prefixed with~(N) in which case it is removed as described below.If FIGNORE is set,then each file name componentthat matches the pattern defined by the value of FIGNORE is ignored when generating the matching filenames.The names. and.. are also ignored.If FIGNORE is not set,the character. at the start of each file name componentwill be ignored unless the first character of the patterncorresponding to this component is the character. itself.Note, that for otheruses of pattern matching the/ and. are not treated specially.

* Matches any string, including the null string.When used for filename expansion,if theglobstar option is on, two adjacent*’s by itselfwill match all files and zero or more directoriesand subdirectories.If followed by a/ then only directories and subdirectories will match.
? Matches any single character.
[...] Matches any one of the enclosed characters.A pair of characters separated by- matches anycharacter lexically between the pair, inclusive.If the first character following the opening[ is a! then any character not enclosed is matched.A- can be included in the character set by putting it as thefirst or last character.
Within[ and], character classes can be specified with the syntax[:class:]where class is one of the following classes defined in the ANSI-C standard:(Note that word is equivalent to alnum plus the character _).

alnum alpha blank cntrl digit graph lower print punct space upper word xdigit

Within[ and], an equivalence class can be specified with the syntax[=c=]which matches all characters with the same primarycollation weight (as defined by the current locale) asthe character c.

Within[ and], [.symbol.]matches the collating symbol symbol.Apattern-list is a list of one or more patterns separated from each otherwith a& or|. A& signifies that all patterns must be matched whereas| requires that only one pattern be matched.Composite patterns can be formed with one or more of the following sub-patterns:

Optionally matches any one of the given patterns.
Matches zero or more occurrences of the given patterns.
Matches one or more occurrences of the given patterns.
Matches n occurrences of the given patterns.
Matches from m to n occurrences of the given patterns.If m is omitted, 0 will be used. If nis omitted at least m occurrences will be matched.
Matches exactly one of the given patterns.
Matches anything except one of the given patterns.

By default, each pattern, or sub-pattern will match thelongest string possible consistent with generatingthe longest overall match. If more than one match ispossible, the one starting closest to the beginningof the string will be chosen. However, for each of the abovecompound patterns a - can be inserted in front of the (to cause the shortest match to the specified pattern-listto be used.

When pattern-list is contained within parentheses,the backslash character \ is treated specially evenwhen inside a character class. All ANSI-C character escapes arerecognized and match the specified character. In additionthe following escape sequences are recognized:

\d Matches any character in the digit class.
\D Matches any character not in the digit class.
\s Matches any character in the space class.
\S Matches any character not in the space class.
\w Matches any character in the word class.
\W Matches any character not in the word class.

A pattern of the form%(pattern-pair(s))is a sub-pattern thatcan be used to match nested character expressions.Eachpattern-pair is a two character sequence which cannot contain& or|. The firstpattern-pair specifies the starting and ending characters for the match.Each subsequentpattern-pair represents the beginning and ending characters of a nested group thatwill be skipped over when counting starting and ending character matches.The behavior is unspecified when the first character of apattern-pair is alpha-numericexcept for the following:

D Causes the ending character to terminate the search for this pattern withoutfinding a match.
E Causes the ending character to be interpreted as an escape character.
L Causes the ending character to be interpreted as a quote charactercausing all characters to be ignored when looking for a match.
Q Causes the ending character to be interpreted as a quote charactercausing all characters other than any escape character to be ignoredwhen looking for a match.

Thus,%({}Q"E\),matches characters starting at{ until the matching} is found not counting any{ or} that is inside a double quoted string or preceded by the escape character\. Without the{} this pattern matches any C language string.

Each sub-pattern in a composite pattern is numbered,starting at 1, by the location of the ( withinthe pattern.The sequence \n, where nis a single digit and \n comes afterthe n-th. sub-pattern,matches the same string as the sub-pattern itself.

Finally a pattern can contain sub-patterns of the form~(options:pattern-list),where either options or :pattern-listcan be omitted. Unlike the other compound patterns,these sub-patterns are not counted in the numbered sub-patterns.If options is present, it can consist of one or moreof the following:

+ Enable the following options. This is the default.
- Disable the following options.
E The remainder of the pattern uses extended regular expression syntaxlike theegrep(1)command.
F The remainder of the pattern usesfgrep(1)expression syntax.
G The remainder of the pattern uses basic regular expression syntaxlike thegrep(1)command.
K The remainder of the pattern uses shell pattern syntax.This is the default.
N This is ignored. However, when it is the first letter and isused with file name generation, and no matches occur,the file pattern expands to the empty string.
i Treat the match as case insensitive.
g File the longest match (greedy). This is the default.
l Left anchor the pattern. This is the default forK style patterns.
r Right anchor the pattern. This is the default forK style patterns.

If both options and :pattern-listare specified, then the options apply only to pattern-list.Otherwise, these options remain in effect until they are disabledby a subsequent ~(...) or at the end ofthe sub-pattern containing ~(...).


Each of themetacharacters listed earlier (seeDefinitions above)has a special meaning to the shelland causes termination of a word unless quoted.A character may bequoted (i.e., made to stand for itself)by precedingit with a\. The pair\new-line is removed.All characters enclosed between a pair of single quote marks('')that is not preceded by a$ are quoted.A single quote cannot appear within the single quotes.A single quoted string preceded by an unquoted$ is processed as an ANSI-C stringexcept for the following:

\0 Causes the remainder of the string to be ignored.
\E Equivalent to the escape character(ascii033),
\e Equivalent to the escape character(ascii033),
\cx Expands to the character control-x.
Expands to the collating element name.

Inside double quote marks(""),parameter and command substitution occur and\ quotes the characters\, `, ",and$. A$ in front of a double quoted string will be ignoredin the "C" or "POSIX" locale, and may causethe string to be replaced by a locale specific string otherwise.The meaning of$* and$@ is identical when not quoted or when used as a variable assignment valueor as a file name.However, when used as a command argument, "$*"is equivalent to"$1d$2d...",whered is the first character of the IFS variable, whereas "$@"is equivalent to "$1" "$2"....Inside grave quote marks(``),\ quotes the characters\, `, and$. If the grave quotes occur within double quotes, then\ also quotes the character".

(Video) Linux and Unix Basics : Korn Shell Command-line Editing

The special meaning of reserved words or aliases can be removed by quoting anycharacter of the reserved word.The recognition of function names or built-in command names listed belowcannot be altered by quoting them.

Arithmetic Evaluation.

The shell performs arithmetic evaluation forarithmetic substitution, to evaluate an arithmetic command,to evaluate an indexed array subscript,and to evaluate arguments tothe built-in commandsshift andlet. Evaluations are performed usingdouble precision floating pointarithmetic or long double precision floating point forsystems that provide this data type.Floating point constants follow the ANSI-C programming languagefloating point conventions.Integer constants follow the ANSI-C programming languageinteger constant conventions although only single bytecharacter constants are recognized and character castsare not recognized.In addition constants can be of the form[base#]nwherebase is a decimal number between two and sixty-fourrepresenting the arithmetic baseandn is a number in that base.The digits above 9 are representedby the lower case letters, the upper case letters,@, and_ respectively.For bases less than or equal to 36, upper and lower casecharacters can be used interchangeably.

An arithmetic expression uses the same syntax, precedence, andassociativity ofexpression as the C language.All the C language operatorsthat apply to floating point quantities can be used.In addition, the operator** can be used for exponentiation.It has higher precedence than multiplication and is left associative.In addition, when the value of an arithmetic variableor sub-expression can be represented as a long integer,all C language integer arithmetic operations can be performed.Variables can be referenced by name within an arithmetic expressionwithout using the parameter expansion syntax.When a variable is referenced, its value is evaluated asan arithmetic expression.

Any of the following math library functions that are in the C math librarycan be used within an arithmetic expression:

abs acos acosh asin asinh atan atan2 atanh cbrt copysign cos cosh erf erfc exp exp2 expm1 fabs fdim finite floor fma fmax fmod j0 j1 jn hypot ilogb int isinf isnan lgamma log log2 logb nearbyint nextafter nexttoward pow rint round sin sinh sqrt tan tanh tgamma trunc y0 y1 yn

An internal representation of avariable as a double precision floating point can be specified with the-E [n],-F [n],or-X [n]option of thetypeset special built-in command.The-E option causes the expansion of the value to be represented usingscientific notation when it is expanded.The optional option argumentn defines the number of significant figures.The-F option causes the expansion to be represented as a floating decimal numberwhen it is expanded.The-X option cause the expansion to be represented using the%a format defined by ISO C-99.The optional option argumentn defines the number of places after the decimal (or radix) point in this case.

An internal integer representation of avariable can be specified with the-i [n]option of thetypeset special built-in command.The optional option argumentn specifies an arithmetic base to be used when expanding the variable.If you do not specify an arithmetic base,base 10 will be used.

Arithmetic evaluation is performed on the value of eachassignment to a variable with the-E, -F, -X, or-i attribute.Assigning a floating point number to avariable whose type is an integer causes the fractionalpart to be truncated.


When used interactively,the shell prompts with the value of PS1 after expanding it for parameter expansion, command substitution, andarithmetic substitution,before reading a command.In addition, each single! in the prompt is replaced by the command number.A!! is required to place! in the prompt.If at any time a new-line is typed and further input is neededto complete a command, then the secondary prompt(i.e., the value ofPS2) is issued.

Conditional Expressions.

Aconditional expression is used with the[[ compound command to test attributes of files and to comparestrings.Field splitting and file name generation arenot performed on the words between[[ and]]. Each expression can be constructed from one or moreof the following unary or binary expressions:

stringTrue, ifstring is not null.
-a fileSame as -e below.This is obsolete.
-b fileTrue, iffile exists and is a block special file.
-c fileTrue, iffile exists and is a character special file.
-d fileTrue, iffile exists and is a directory.
-e fileTrue, iffile exists.
-f fileTrue, iffile exists and is an ordinary file.
-g fileTrue, iffile exists and it has its setgid bit set.
-k fileTrue, iffile exists and it has its sticky bit set.
-n string
True, if length ofstring is non-zero.
-o ?option
True, if option namedoption is a valid option name.
-o option
True, if option namedoption is on.
-p fileTrue, iffile exists and is a fifo special file or a pipe.
-r fileTrue, iffile exists and is readable by current process.
-s fileTrue, iffile exists and has size greater than zero.
-t fildes
True, if file descriptor numberfildes is open and associated with a terminal device.
-u fileTrue, iffile exists and it has its setuid bit set.
-w fileTrue, iffile exists and is writable by current process.
-x fileTrue, iffile exists and is executable by current process.Iffile exists and is a directory, then true if the current processhas permission to search in the directory.
-z string
True, if length ofstring is zero.
-L fileTrue, iffile exists and is a symbolic link.
-h fileTrue, iffile exists and is a symbolic link.
-N fileTrue, iffile exists and the modification time is greater than the last access time.
-O fileTrue, iffile exists and is owned by the effective user id of this process.
-G fileTrue, iffile exists and its group matches the effective group id of this process.
-S fileTrue, iffile exists and is a socket.
file1 -nt file2
True, iffile1 exists andfile2 does not, orfile1 is newer thanfile2.
file1 -ot file2
True, iffile2 exists andfile1 does not, orfile1 is older thanfile2.
file1 -ef file2
True, iffile1 andfile2 exist and refer to the same file.
string == pattern
True, ifstring matchespattern. Any part ofpattern can be quoted to cause it to be matched as a string.With a successful match to a pattern, the.sh.match array variable will contain the match and sub-pattern matches.
string = pattern
Same as == above, but is obsolete.
string != pattern
True, ifstring does not matchpattern. When thestring matches thepattern the.sh.match array variable will contain the match and sub-pattern matches.
string =~ ere
True ifstring matches the pattern~(E)ere whereere is an extended regular expression.
string1 < string2
True, ifstring1 comes beforestring2 based on ASCII value of their characters.
string1 > string2
True, ifstring1 comes afterstring2 based on ASCII value of their characters.
The following obsolete arithmetic comparisons are also permitted:
exp1 -eq exp2
True, ifexp1 is equal toexp2.
exp1 -ne exp2
True, ifexp1 is not equal toexp2.
exp1 -lt exp2
True, ifexp1 is less thanexp2.
exp1 -gt exp2
True, ifexp1 is greater thanexp2.
exp1 -le exp2
True, ifexp1 is less than or equal toexp2.
exp1 -ge exp2
True, ifexp1 is greater than or equal toexp2.
In each of the above expressions, iffile is of the form/dev/fd/n,wheren is an integer,then the test is applied to the open file whosedescriptor number isn.
A compound expression can be constructed from these primitives byusing any of the following, listed in decreasing order of precedence.
True, ifexpression is true.Used to group expressions.
! expression
True ifexpression is false.
expression1 && expression2
True, ifexpression1 andexpression2 are both true.
expression1 || expression2
True, if eitherexpression1 orexpression2 is true.


Before a command is executed, its input and outputmay be redirected using a special notation interpreted by the shell.The following may appear anywhere in a simple-commandor may precede or follow acommand and arenot passed on to the invoked command.Command substitution, parameter expansion,and arithmetic substitution occur beforeword ordigit is used except as noted below.File name generationoccurs only if the shell is interactive andthe pattern matches a single file.Field splitting is not performed.

In each of the following redirections, iffile is of the form/dev/sctp/host/port,/dev/tcp/host/port,or/dev/udp/host/port,wherehost is a hostname or host address,andport is a service given by name or an integer port number,then the redirection attempts to make atcp, sctp or udp connection to the correspondingsocket.

No intervening space is allowed between the characters of redirection operators.

<word Use fileword as standard input (file descriptor 0).
>word Use fileword as standard output (file descriptor 1).If the file does not exist then it is created.If the file exists, and thenoclobber option is on,this causes an error;otherwise, it is truncated to zero length.
>|word Sames as>, except that it overrides thenoclobber option.
>;word Write output to a temporary file. If the command completessuccessfully rename it toword, otherwise, delete the temporary file.>;word cannot be used with theexec(2).built-in.
>>word Use fileword as standard output.If the file exists, then output is appended to it (by first seeking to the end-of-file);otherwise, the file is created.
<>word Open fileword for reading and writingas standard output.
<>;word The same as<>word except that if the command completes successfully,word is truncated to the offset at command completion.<>;word cannot be used with theexec(2).built-in.
<<[-]wordThe shell input is read up to a line that is the same asword after any quoting has been removed,or to an end-of-file.No parameter substitution, command substitution, arithmetic substitution orfile name generation is performed onword. The resulting document,called ahere-document, becomesthe standard input.If any character ofword is quoted, then no interpretationis placed upon the characters of the document;otherwise, parameter expansion, command substitution, and arithmeticsubstitution occur,\new-line is ignored,and\ must be used to quote the characters\, $, `. If- is appended to<<, then all leading tabs are stripped fromword and from the document.If# is appended to<<, then leading spaces and tabs will be stripped off the firstline of the document and up to an equivalent indentation willbe stripped from the remaining lines and fromword. A tab stop is assumed to occur at every 8 columns for thepurposes of determining the indentation.
<<<wordA short form of here document in which word becomes thecontents of the here-document after anyparameter expansion, command substitution, and arithmeticsubstitution occur.
<&digit The standard input is duplicated from file descriptordigit (seedup(2)).Similarly for the standard output using>&digit.
<&digit- The file descriptor given bydigit is moved to standard input.Similarly for the standard output using>&digit-.
<&- The standard input is closed.Similarly for the standard output using>&-.
<&p The input from the co-process is moved to standard input.
>&p The output to the co-process is moved to standard output.
<#((expr)) Evaluate arithmetic expressionexpr and position file descriptor 0to the resulting valuebytes from the start of the file.The variablesCUR andEOF evaluate to the current offset and end-of-file offsetrespectively when evaluatingexpr.
>#((offset)) The same as<# except applies to file descriptor 1.
<#pattern Seeks forward to the beginning of the next line containingpattern.
<##pattern The same as<# except that the portion of the file that is skipped is copied tostandard output.

If one of the above is preceded by a digit,with no intervening space, then thefile descriptor number referred to is that specifiedby the digit(instead of the default 0 or 1).If one of the above, other than>&- and the># and<# forms,is preceded by{varname} with no intervening space,then a file descriptor number > 10will be selected bythe shell and stored in the variablevarname. If>&- or the any of the># and<# formsis preceded by{varname} the value ofvarname defines the file descriptor to close or position.For example:

... 2>&1

means file descriptor 2 is to be openedfor writing as a duplicateof file descriptor 1 and

exec {n}<file

means open file namedfile for reading and storethe file descriptor number in variablen.

The order in which redirections are specified is significant.The shell evaluates each redirection in terms of the(file descriptor, file) association at the time of evaluation.For example:

... 1>fname 2>&1

first associates file descriptor 1 with filefname. It then associates file descriptor 2 with the file associated with filedescriptor 1 (i.e.fname). If the order of redirections were reversed, file descriptor 2 would be associatedwith the terminal (assuming file descriptor 1 had been) and then file descriptor1 would be associated with filefname.

If a command is followed by& and job control is not active,then the default standard inputfor the commandis the empty file/dev/null. Otherwise, the environment for the execution of a command contains thefile descriptors of the invoking shell as modified byinput/output specifications.


Theenvironment (seeenviron(7))is a list of name-value pairs that is passed toan executed program in the same way as a normal argument list.The names must beidentifiers and the values are character strings.The shell interacts with the environment in several ways.On invocation, the shell scans the environmentand creates avariablefor each name found,giving it the corresponding value and attributes and marking itexport. Executed commands inherit the environment.If the user modifies the values of thesevariablesor creates new ones,using theexport ortypeset -x commands, they become part of theenvironment.The environment seen by any executed command is thus composedof any name-value pairs originally inherited by the shell,whose values may be modified by the current shell,plus any additionswhich must be noted inexport ortypeset -x commands.

The environment for anysimple-command or functionmay be augmented by prefixing it with one or more variable assignments.A variable assignment argument is a word of the formidentifier=value. Thus:

TERM=450 cmd argsand
(export TERM; TERM=450; cmd args)

are equivalent (as far as the above execution ofcmd is concerned except for special built-in commands listed below -those that arepreceded with a dagger).

If the obsolete-k option is set,all variable assignment arguments are placed in the environment,even if they occur after the command name.The followingfirst printsa=b c and thenc:

echo a=b cset -kecho a=b c

This feature is intended for use with scripts writtenfor early versions of the shell and its use in new scriptsis strongly discouraged.It is likely to disappear someday.


For historical reasons, there are twoways to define functions,thename() syntax andthefunction name syntax, described in theCommands section above.Shell functions are read in and stored internally.Alias names are resolved when the function is read.Functions are executed like commands with the argumentspassed as positional parameters.(SeeExecution below.)

Functions defined by thefunction name syntax and called by name execute in the same process as the caller andshare all filesand present working directory with thecaller.Traps caught by the caller are reset to their default actioninside the function.A trap condition that is not caught or ignored by thefunction causes the function to terminate and the conditionto be passed on to the caller.A trap on EXIT set inside a functionis executedin the environmentof the callerafter the function completes.Ordinarily,variables are shared between the calling programand the function.However,thetypeset special built-in command used within a functiondefines local variables whose scope includesthe current function.They can be passed to functions that they call in thevariable assignment list that precedes the call or as argumentspassed as name references.Errors within functions return control to the caller.

Functions defined with thename() syntax and functions defined with thefunction name syntax that are invoked with the .special built-inare executed in the caller’senvironment and share all variablesand traps with the caller.Errors within these function executions cause the script that containsthem to abort.

The special built-in commandreturn is used to returnfrom function calls.

Function namescan be listed with the-f or+f option of thetypeset special built-in command.The text of functions, when available, will alsobe listed with-f. Functions can be undefined with the-f option of theunset special built-in command.

Ordinarily, functions are unset when the shell executes a shell script.Functions that need to be defined across separateinvocations of the shell shouldbe placed in a directory and the FPATHvariable should contain the name of this directory.They may alsobe specified in the ENVfile.

Discipline Functions.

Each variable can have zero or more discipline functionsassociated with it.The shell initially understands the discipline names get,set, append, and unset but can be addedwhen defining new types. On most systemsothers can be added at run time via theC programming interface extension provided by thebuiltin built-in utility.If the get discipline is defined for a variable, it is invokedwhenever the given variable is referenced.If the variable .sh.value is assigned a value insidethe discipline function, the referenced variable will evaluateto this value instead.If the set discipline is defined for a variable, it is invokedwhenever the given variable is assigned a value.If the append discipline is defined for a variable, it is invokedwhenever a value is appended to the given variable.The variable .sh.value is given the valueof the variable before invoking the discipline, andthe variable will be assigned the value of .sh.valueafter the discipline completes.If .sh.value is unset inside the discipline, thenthat value is unchanged.If the unset discipline is defined for a variable, it is invokedwhenever the given variable is unset.The variable will not be unset unless it is unset explicitlyfrom within this discipline function.

The variable.sh.name contains the name of the variable for which the discipline function is called,.sh.subscript is the subscript of the variable, and.sh.value will contain the value being assigned inside theset discipline function.The variable_ is a reference to the variable including the subscript if any.For the set discipline,changing.sh.value will change the value that gets assigned.Finally, the expansion ${var.name},when name is the name of a discipline, and there isno variable of this name, is equivalent to the command substitution${ var.name;}.

Type Variables.

Typed variables provide a way to create data structure and objects.A type can be defined either by a shared library, by theenum built-in command described below, or by using the new-T option of thetypeset built-in command.With the-T option oftypeset, the type name, specified as an option argument to-T, is set with a compound variable assignment that defines the type.Function definitions can appear inside the compound variableassignment and these become discipline functions for this type andcan be invoked or redefined by each instance of the type.The function namecreate is treated specially. It is invoked for each instance ofthe type that is created but is not inherited and cannot beredefined for each instance.

(Video) Linux Crash Course - The sed Command

When a type is defined a special built-in command of that nameis added. These built-ins are declaration commands and follow thesame expansion rules as all the special built-in commands definedbelow that are preceded by ††. These commands can subsequentlybe used inside further type definitions. The man page for these commands canbe generated by using the--man option or any of the other-- options described withgetopts. The-r, -a, -A, -h, and-S options oftypeset are permitted with each of these new built-ins.

An instance of a type is created by invoking the type namefollowed by one or more instance names.Each instance of the type is initialized with a copy of the sub-variablesexcept for sub-variables that are defined with the-S option. Variables defined with the-S are shared by all instances of the type.Each instance can change the value of any sub-variable and can alsodefine new discipline functions of the same namesas those defined by the type definition as well as anystandard discipline names.No additional sub-variables can be defined for any instance.

When defining a type,if the value of a sub-variable is not set and the-r attribute is specified, it causes the sub-variableto be a required sub-variable.Whenever an instance of a type is created, all required sub-variablesmust be specified.These sub-variables become readonly in each instance.

Whenunset is invoked on a sub-variable within a type,and the-r attribute has not been specified for this field,the value is reset to the default value associative withthe type.Invokingunset on a type instance not contained within another type deletesall sub-variables and the variable itself.

A type definition can be derived from another type definitionby defining the first sub-variable name as_ and defining its type as the base type.Any remaining definitions will be additions and modificationsthat apply to the new type.If the new type name is the same is that of the base type,the type will be replaced and the original type willno longer be accessible.


If themonitor option of theset command is turned on,an interactive shell associates a job with each pipeline.It keepsa table of current jobs, printed by thejobs command, and assigns them small integer numbers.When a job is started asynchronously with&, the shell prints a line which lookslike:

[1] 1234

indicating that the job which was started asynchronously was job number1 and had one (top-level) process, whose process id was 1234.

This paragraph and the next require features that arenot in all versions of UNIX and may not apply.If you are running a job and wish to do something else you may hit the key^Z (control-Z) which sends a STOP signal to the current job.The shell will then normally indicate that the job has been ‘Stopped’,and print another prompt.You can then manipulate the state of this job,putting it in the background with thebg command, or run some othercommands and then eventually bring the job back into the foreground withthe foreground commandfg. A ^Z takes effect immediately andis like an interrupt in that pending output and unread input are discardedwhen it is typed.

A job being run in the background will stop if it tries to readfrom the terminal.Background jobs are normally allowed to produce output,but this can be disabled by giving the commandstty tostop. If you set thistty option, then background jobs will stop when they try to produceoutput like they do when they try to read input.

There are several ways to refer to jobs in the shell.A job can be referred to by the process id of any process of the jobor by one of the following:

The job with the given number.
Any job whose command line begins withstring.
Any job whose command line containsstring.
%% Current job.
%+ Equivalent to%%.
%- Previous job.

The shell learns immediately whenever a process changes state.It normally informs you whenever a job becomes blocked so thatno further progress is possible, but only just before it printsa prompt.This is done so that it does not otherwise disturb your work.Thenotify option of theset command causesthe shell to print these job change messagesas soon as they occur.

When themonitor option is on, each background job that completestriggers any trap set forCHLD.

When you try to leave the shell while jobs are running or stopped, you willbe warned that ‘You have stopped(running) jobs.’You may use thejobs command to see what they are.If you immediately try toexit again, the shell will not warn you a second time, and the stoppedjobs will be terminated.When a login shell receives a HUP signal, it sendsa HUP signal to each job that has not been disowned with thedisown built-in command described below.


The INT and QUIT signals for an invokedcommand are ignored if the command is followed by& and themonitor option is not active.Otherwise, signals have the valuesinherited by the shell from its parent(but see alsothetrap built-in command below).


Each time a command is read, the above substitutionsare carried out.If the command name matches oneof theSpecial Built-in Commands listed below,it is executed within thecurrent shell process.Next, the command name is checked to see ifit matches a user defined function.If it does,the positional parameters are savedand then reset to the arguments of thefunction call.A function is also executed in thecurrent shell process.When thefunction completes or issues areturn, the positional parameter list is restored.For functions defined with thefunction name syntax,any trap set on EXIT within the function is executed.The exit value of afunction is the value of the last command executed.If a command name is not aspecial built-in command or a user definedfunction, but it is one of the built-in commands listed below,it is executed in the current shell process.

The shell variable PATH defines the search path forthe directory containing the command.Alternative directory names are separated bya colon(:). The default path is/bin:/usr/bin: (specifying/bin, /usr/bin, and the current directoryin that order).The current directory can be specified bytwo or more adjacent colons, or by a colonat the beginning or end of the path list.If the command name contains a /, then the search pathis not used.Otherwise, each directory in the path issearched for an executable fileof the given namethat is not a directory.If found, and if the shelldetermines that there is a built-in versionof a command corresponding to a given pathname,this built-in is invoked in the current process.If found, and this directory is also contained in the value of the FPATH variable,then this file is loaded into the current shell environmentas if it were the argument to the . commandexcept that only preset aliases are expanded,and a function of the given name is executedas described above.If not found, and the file.paths is found, and this file contains a line of the formFPATH=path wherepath names anexisting directory, and this directory containsa file of the given name,then this file is loaded into the current shell environmentas if it were the argument to the . special built-in commandand a function of the given name is executed.Otherwise, if found,a process is created andan attempt is made to execute the command viaexec(2).

When an executable is found, the directory where it is foundin is searched for a file named.paths. If this file is found and it contains a line of the formBUILTIN_LIB=value , then the library named byvalue will be searched for as if it were an option argument tobuiltin -f, and if it contains a built-in of the specified namethis will be executed instead of a command by this name.Otherwise, if this file is found and it contains a line of the formname=value in the first or second line, then the environment variablename is modified by prepending the directory specified byvalue to the directory list.Ifvalue is not an absolute directory, then itspecifies a directory relative to the directory that theexecutable was found.If the environment variablename does not already exist it will be added to the environmentlist for the specified command.

If the file has execute permission but is not ana.out file,it is assumed to be a file containing shell commands.A separate shell is spawned to read it.All non-exported variables are removed in this case.If the shell commandfile doesn’t have read permission,or if thesetuid and/orsetgid bits are set on the file,then the shell executes an agent whose job it is toset up the permissions and execute the shell with theshell command file passed down as an open file.A parenthesized command is executed ina sub-shell without removing non-exported variables.

Command Re-entry.

The text of the last HISTSIZE(default 512)commands entered from a terminal deviceis saved in ahistory file.The file$HOME/.sh_history is used if the HISTFILEvariable is not setor if the file it names is not writable.A shell can access the commands ofallinteractive shells which use the same named HISTFILE. The built-in commandhist is used to list oredit a portion of this file.The portion of the file to be edited or listed can be selected bynumber or by giving the first character orcharacters of the command.A single command or range of commands can be specified.If you do not specify an editor program asan argument tohist then the value of the variable HISTEDIT is used.If HISTEDIT is unset, the obsolete variable FCEDIT is used.If FCEDIT is not defined, then/bin/ed is used.The edited command(s) is printed and re-executed uponleaving the editor unless you quit without writing.The-s option(and in obsolete versions, the editor name-) is used to skip the editing phase andto re-execute the command.In this case a substitution parameter of the formold=newcan be used to modify the command before execution.For example, with the preset aliasr, which is aliased to'hist -s', typing‘r bad=good c’will re-execute the most recent command which starts with the letterc, replacing the first occurrence of the stringbad with the stringgood.

In-line Editing Options.

Normally, each command line entered from a terminal device is simplytyped followed by a new-line (‘RETURN’ or ‘LINE FEED’).If either theemacs, gmacs, orvi option is active, the user can edit the command line.To be in either of these edit modesset the correspondingoption.An editing option is automatically selected each time the VISUAL or EDITOR variable is assigned a value ending in either of theseoption names.

The editing features require that the user’s terminalaccept ‘RETURN’ as carriage return without line feedand that a space (‘ ’) must overwrite the current character onthe screen.

Unless themultiline option is on,the editing modes implement a concept where the user is looking through awindow at the current line.The window width is the value of COLUMNS if it is defined, otherwise 80.If the window width is too small to display the prompt and leaveat least 8 columns to enter input, the prompt is truncated from theleft.If the line is longer than the window width minus two, a mark isdisplayed at the end of the window to notify the user.As the cursor moves and reaches the window boundaries the window will becentered about the cursor.The mark is a> (<, *) if the line extends on theright (left, both) side(s) of the window.

The search commands in each edit mode provide access to the history file.Only strings are matched, not patterns, although a leading^ in the string restricts the matchto begin at the first character in the line.

Each of the edit modes has an operation to list the filesor commands that match a partially entered word.When applied to the first word on the line,or the first word after a;, |, &, or(, and the word does not begin with~ or contain a/, the list of aliases, functions, and executable commandsdefined by the PATH variable that could match the partial word is displayed.Otherwise, the list of files that match the givenword is displayed.If the partially entered word does not contain anyfile expansion characters, a* is appended before generating these lists.After displaying the generated list, the input lineis redrawn.These operations are called command name listing and file name listing,respectively.There are additional operations, referred to as command namecompletion and file name completion, which compute the listof matching commands or files, but instead of printing the list,replacethe current word with a complete or partial match.For file name completion,if the match is unique, a/ is appended if the file is a directory and a space isappended if the file is not a directory.Otherwise, the longest common prefix for all the matchingfiles replaces the word.For command name completion, only the portion of the file namesafter the last/ are used to find the longest command prefix.If only a single name matches this prefix, then theword is replaced with the command name followed by a space.When using atab for completion that does not yield a unique match,a subsequenttab will provide a numbered list of matching alternatives.A specific selection can be made by entering theselection number followed by atab.

Key Bindings.

The KEYBD trap can be used to intercept keys as they are typedand change the characters that are actually seen bythe shell.This trap is executed after each character(or sequence of characters when the first character is ESC)is entered while reading from a terminal.The variable.sh.edchar contains the character or character sequence whichgenerated the trap.Changing the value of.sh.edchar in the trap action causes the shell to behave as if thenew value were entered from the keyboard rather thanthe original value.

The variable.sh.edcol is set to the input column number of the cursor at the timeof the input.The variable.sh.edmode is set toESCwhen invi insert mode (see below) and is null otherwise.By prepending${.sh.editmode} to a value assigned to.sh.edchar it will cause the shellto change to control mode if it is not already in this mode.

This trap is not invoked for characters entered as arguments toediting directives, or while reading input for a character search.

Emacs Editing Mode.

This mode is entered by enabling either theemacs orgmacs option.The only difference between these two modes is the waythey handle^T. To edit, the usermoves the cursor to the point needing correction andthen inserts or deletes characters or words as needed.All the editing commands are control characters or escapesequences.The notation for control characters is caret(^) followedby the character.For example,^F is the notation for controlF. This is entered by depressing ‘f’ while holding down the‘CTRL’ (control) key.The ‘SHIFT’ key isnot depressed.(The notation^? indicates the DEL (delete) key.)

The notation for escape sequences isM- followed by acharacter.For example,M-f (pronounced Meta f)is entered by depressing ESC(ascii033) followed by ‘f’.(M-F would be the notation for ESC followed by ‘SHIFT’ (capital) ‘F’.)

All edit commandsoperate from any place on the line(not just at the beginning).Neither the ‘RETURN’ nor the ‘LINE FEED’ key isentered after edit commands except when noted.

^F Move cursor forward (right) one character.
M-[C Move cursor forward (right) one character.
M-f Move cursor forward one word.(Theemacs editor’s idea of a word is a string of charactersconsisting of only letters, digits and underscores.)
^B Move cursor backward (left) one character.
M-[D Move cursor backward (left) one character.
M-b Move cursor backward one word.
^A Move cursor to start of line.
M-[H Move cursor to start of line.
^E Move cursor to end of line.
M-[Y Move cursor to end of line.
^]char Move cursor forward to characterchar on current line.
M-^]char Move cursor backward to characterchar on current line.
^X^X Interchange the cursor and mark.
erase (User defined erase character as definedby thestty(1)command, usually^H or#.) Delete previous character.
lnext (User defined literal next character as definedby thestty(1)command,or^V if not defined.)Removes the next character’sediting features (if any).
^D Delete current character.
M-d Delete current word.
M-^H (Meta-backspace) Delete previous word.
M-h Delete previous word.
M-^? (Meta-DEL) Delete previous word (if your interrupt character is^? (DEL, the default) then this command will not work).
^T Transpose current character with previous characterand advance the cursorinemacs mode.Transpose two previous characters ingmacs mode.
^C Capitalize current character.
M-c Capitalize current word.
M-l Change the current word to lower case.
^K Delete from the cursor to the end of the line.If preceded by a numerical parameter whose value is less than thecurrent cursor position, then delete from given positionup to the cursor.If preceded by a numerical parameter whose value is greater than thecurrent cursor position, then delete from cursor up togiven cursor position.
^W Kill from the cursor to the mark.
M-p Push the region from the cursor to the mark on the stack.
kill (User defined kill character as definedby the stty command, usually^G or@.) Kill the entire current line.If twokill characters are entered in succession, allkill characters from then on cause a line feed(useful when using paper terminals).
^Y Restore last item removed from line. (Yank item back to the line.)
^L Line feed and print current line.
M-^L Clear the screen.
^@ (Null character) Set mark.
M-space (Meta space) Set mark.
^J (New line) Execute the current line.
^M (Return) Execute the current line.
eof End-of-file character,normally^D, is processed as an End-of-file onlyif the current line is null.
^P Fetch previous command.Each time^P is enteredthe previous command back in time is accessed.Moves back one line when not on the first line of a multi-line command.
M-[A If the cursor is at the end of the line, it is equivalent to^R withstring set to the contents of the current line.Otherwise, it isequivalent to^P.
M-< Fetch the least recent (oldest) history line.
M-> Fetch the most recent (youngest) history line.
^N Fetch next command line.Each time^N is enteredthe next command line forward in time is accessed.
M-[B Equivalent to^N.
^Rstring Reverse search history for a previous command line containingstring. If a parameter of zero is given, the search is forward.String is terminated by a ‘RETURN’ or ‘NEW LINE’.If string is preceded by a^, the matched line must begin withstring. Ifstring is omitted,then the next command line containing the most recentstring is accessed.In this case a parameter of zeroreverses the direction of the search.
^O Operate - Execute the current line and fetchthe next line relative to current line from thehistory file.
M-digits (Escape) Define numeric parameter, the digitsare taken as a parameter to the next command.The commands that accept a parameter are^F, ^B, erase, ^C, ^D, ^K, ^R, ^P, ^N, ^], M-., M-^], M-_, M-=, M-b, M-c, M-d, M-f, M-h, M-l andM-^H.
M-letter Soft-key - Your alias list is searched for analias by the name_letter and if an alias of this name is defined, itsvalue will be inserted on the input queue.Theletter must not be one of the above meta-functions.
M-[letter Soft-key - Your alias list is searched for analias by the name__letter and if an alias of this name is defined, itsvalue will be inserted on the input queue.This can be used to program function keys on many terminals.
M-. The last word of the previous command is insertedon the line.If preceded by a numeric parameter, the valueof this parameter determines which word to insert rather thanthe last word.
M-_ Same asM-..
M-* Attempt file name generation on the current word.An asterisk is appended if the word doesn’t match any fileor contain any specialpattern characters.
M-ESC Command or file name completion as described above.
^I tab Attempts command or file name completion as described above.If a partial completion occurs, repeating this willbehave as ifM-= were entered.If no match is found or entered afterspace, atab is inserted.
M-= If not preceded by a numeric parameter,it generates the list of matching commands orfile names as described above.Otherwise, the word under the cursor is replaced bythe item corresponding to the value of the numeric parameterfrom the most recently generated command or file list.If the cursor is not on a word, it is inserted instead.
^U Multiply parameter of next command by 4.
\ Escape next character.Editing characters, the user’s erase, kill andinterrupt (normally^?) charactersmay be enteredin a command line or in a search string if preceded by a\. The\ removes the next character’sediting features (if any).
M-^V Display version of the shell.
M-# If the line does not begin with a#, a# is insertedat the beginning of the lineand after each new-line,and the line is entered.This causes a comment to be inserted in the history file.If the line begins with a#, the# is deleted and one# after each new-line is also deleted.

Vi Editing Mode.

There are two typing modes.Initially, when you enter a command you are in theinput mode.To edit, the user enterscontrol mode by typing ESC(033) and moves the cursor to the point needing correction andthen inserts or deletes characters or words as needed.Most control commands accept an optional repeatcount prior to the command.

When invi mode on most systems,canonical processing is initially enabled and thecommand will be echoed again if the speed is 1200 baud or greater and itcontains any control characters or less than one second has elapsedsince the prompt was printed.The ESC character terminates canonical processing for the remainder of the commandand the user can then modify the command line.This scheme has the advantages of canonical processing with the type-aheadechoing of raw mode.

If the optionviraw is also set, the terminal will always have canonical processingdisabled.This mode is implicit for systems that do not support twoalternate end of line delimiters,and may be helpful for certain terminals.

Input Edit Commands

By default the editor is in input mode.

erase (User defined erase character as definedby the stty command, usually^H or#.) Delete previous character.
^W Delete the previous blank separated word.On some systems the viraw optionmay be required for this to work.
eof As the first character of the line causesthe shell to terminate unless the ignoreeofoption is set.Otherwise this character is ignored.
lnext (User defined literal next character as definedby thestty(1)or^V if not defined.)Removes the next character’sediting features (if any).On some systems the viraw optionmay be required for this to work.
\ Escape the nexterase orkill character.
^I tab Attempts command or file name completion as described aboveand returns to input mode.If a partial completion occurs, repeating this willbehave as if= were entered from control mode.If no match is found or entered afterspace, atab is inserted.

Motion Edit Commands

These commands will move the cursor.

[count]lCursor forward (right) one character.
[count][CCursor forward (right) one character.
[count]wCursor forward one alpha-numeric word.
[count]WCursor to the beginning of the next word that follows a blank.
[count]eCursor to end of word.
[count]ECursor to end of the current blank delimited word.
[count]hCursor backward (left) one character.
[count][DCursor backward (left) one character.
[count]bCursor backward one word.
[count]BCursor to preceding blank separated word.
[count]|Cursor to columncount.
[count]fcFind the next character c in the current line.
[count]FcFind the previous character c in the current line.
[count]tcEquivalent tof followed byh.
[count]TcEquivalent toF followed byl.
[count];Repeatscount times,the last single character find command,f, F, t, orT.
[count],Reverses the last single character find commandcount times.
0 Cursor to start of line.
^ Cursor to start of line.
[H Cursor to first non-blank character in line.
$ Cursor to end of line.
[Y Cursor to end of line.
% Moves to balancing(, ), {, }, [, or]. If cursor is not on one of the above characters,the remainder of the line is searched for the firstoccurrence of one of the above characters first.

Search Edit Commands

These commands access your command history.

[count]kFetch previous command.Each timek is enteredthe previous command back in time is accessed.
[count]-Equivalent tok.
[count][AIf cursor is at the end of the line it is equivalent to/ withstring^ set to the contents of the current line.Otherwise, it is equivalent tok.
[count]jFetch next command.Each timej is enteredthe next command forward in time is accessed.
[count]+Equivalent toj.
[count][BEquivalent toj.
[count]GThe command numbercount is fetched.The default is the least recent history command.
/string Search backward through history for a previous command containingstring. String is terminated by a ‘RETURN’ or ‘NEW LINE’.If string is preceded by a^, the matched line must begin withstring. If string is null, the previous string will be used.
?string Same as/ except that search will be in the forward direction.
n Search for next match of the last pattern to/ or? commands.
N Search for next match of the last pattern to/ or?, but in reverse direction.

Text Modification Edit Commands

These commands will modify the line.

(Video) ksh: The keyboard shortcuts I use everyday

a Enter input mode and enter text after the current character.
A Append text to the end of the line.Equivalent to$a.
Delete current character through the character thatmotion would move the cursor to and enter input mode.If motion isc, the entire line will be deleted andinput mode entered.
C Delete the current character through the end of line and enter input mode.Equivalent toc$.
S Equivalent tocc.
[count]sReplace characters under the cursor in input mode.
D Delete the current character through the end of line.Equivalent tod$.
Delete current character through the character thatmotion would move to.If motion isd , the entire line will be deleted.
i Enter input mode and insert text before the current character.
I Insert text before the beginning of the line.Equivalent to0i.
[count]PPlace the previous text modification before the cursor.
[count]pPlace the previous text modification after the cursor.
R Enter input mode andreplace characters on the screen with characters you type overlay fashion.
[count]rcReplace thecount character(s) starting at the current cursor position withc, and advance the cursor.
[count]xDelete current character.
[count]XDelete preceding character.
[count].Repeat the previous text modification command.
[count]~Invert the case of thecount character(s) starting at the current cursor position and advance the cursor.
[count]_Causes thecount word of the previous command to be appended andinput mode entered.The last word is usedifcount is omitted.
* Causes an* to be appended to the current word and file name generation attempted.If no match is found,it rings the bell.Otherwise, the word is replacedby the matching pattern and input mode is entered.
\ Command or file name completion as described above.

Other Edit Commands

Miscellaneous commands.

Yank current character through character thatmotion would move the cursor to and puts them into the delete buffer.The text and cursor are unchanged.
yy Yanks the entire line.
Y Yanks from current position to end of line.Equivalent toy$.
u Undo the last text modifying command.
U Undo all the text modifying commands performed on the line.
[count]vReturns the commandhist -e ${VISUAL:-${EDITOR:-vi}} count in the input buffer.Ifcount is omitted, then the current line is used.
^L Line feed and print current line.Has effect only in control mode.
^J (New line) Execute the current line, regardless of mode.
^M (Return) Execute the current line, regardless of mode.
# If the first character of the command is a#, then this command deletes this# and each# that follows a newline.Otherwise,sends the line afterinserting a# in front of each line in the command.Useful for causing the current line to beinserted in the history as a comment anduncommenting previously commented commandsin the history file.
[count]=If count is not specified,it generates the list of matching commands orfile names as described above.Otherwise, the word under the the cursor is replaced by thecount item from the most recently generated command or file list.If the cursor is not on a word, it is inserted instead.
@letter Your alias list is searched for analias by the name_letter and if an alias of this name is defined, itsvalue will be inserted on the input queue for processing.
^V Display version of the shell.

Built-in Commands.

The following simple-commands are executed in the shell process.Input/Output redirection is permitted.Unless otherwise indicated, the output is written on file descriptor 1and the exit status, when there is no syntax error, is zero.Except for:, true, false, echo, newgrp, andlogin, all built-in commands accept-- to indicate end of options.They also interpret the option--man as a request to display the man page ontostandard error and-? as a help request which prints ausage messageon standard error.Commands that are preceded by one or two † symbolsare special built-in commands andare treated specially in the following ways:

1.Variable assignment lists preceding the commandremain in effect when the command completes.
2.I/O redirections are processed after variable assignments.
3.Errorscause a scriptthat contains them to abort.
4.They are not valid function names.
5.Wordsfollowing a command preceded by ††that are in the format of a variable assignmentare expanded with the same rules as a variable assignment.This means thattilde substitution is performed after the= sign and field splitting and file name generation are notperformed.These are calleddeclaration built-ins.
† : [ arg ... ]
The command only expands parameters.
† . name [ arg ... ]
Ifname is a function defined with thefunction name reserved word syntax,the function is executed in the current environment(as if it had been defined with thename() syntax.)Otherwise ifname refers to a file, thefile is read in its entirety and the commands areexecuted in the current shell environment.The search pathspecified by PATH is used to find the directory containing the file.If any argumentsarg are given,they become the positional parameters while processingthe. command and the original positional parameters are restored upon completion.Otherwise the positional parameters are unchanged.The exit status is the exit status of the last command executed.
†† alias [ -ptx ] [ name[ =value ] ] ...
alias with no arguments prints the list of aliasesin the formname=value on standard output.The-p optioncauses the wordalias to be inserted before each one.When one or more arguments are given,analias is definedfor eachname whosevalue is given.A trailing space invalue causes the next word to be checked foralias substitution.The obsolete-t option is used to set and list tracked aliases.The value of a tracked alias is the full pathnamecorresponding to the givenname. The value becomes undefined when the value of PATH is reset but the alias remains tracked.Without the-t option,for eachname in the argument listfor which novalue is given, the nameand value of the alias is printed.The obsolete-x option has no effect.The exit status is non-zero if aname is given, but no value, and no alias has been defined for thename.
bg [ job... ]
This command is only on systems that support job control.Puts each specifiedjob into the background.The current job is put in the backgroundifjob is not specified.SeeJobs for a description of the format ofjob.
† break [ n ]
Exit from the enclosingfor, while, until, orselect loop, if any.Ifn is specified, then breakn levels.
builtin [ -ds ] [ -f file ] [ name ... ]
Ifname is not specified,and no-f option is specified,the built-ins are printed on standard output.The-s option prints only the special built-ins.Otherwise, eachname represents the pathname whose basename is the name of the built-in.The entry point function name is determined by prependingb_ to the built-in name.The ISO C/C++ prototype isb_mycommand(int argc, char *argv[], void *context)for the builtin commandmycommand whereargv is array an ofargc elements and context is an optional pointer to aShell_t structure as described in<ast/shell.h>.

Special built-ins cannot be bound to a pathname or deleted.The-d option deletes each of the given built-ins.On systems that support dynamic loading, the-f option names a shared library containing the code for built-ins.The shared library prefix and/or suffix, which depend on the system,can be omitted.Once a library is loaded, its symbols become availablefor subsequent invocations ofbuiltin. Multiple libraries can be specified with separate invocationsof thebuiltin command.Libraries are searched in the reverse order in which they are specified.When a library is loaded, it looks for a function in the librarywhose name islib_init() and invokes this function with an argument of0.

cd [ -LP ] [ arg ]
cd [ -LP ] old new
This command can be in either of two forms.In the first form itchanges the current directory toarg. Ifarg is- the directory is changed to the previousdirectory.The shellvariable HOME is the defaultarg. The variable PWD is set to the current directory.The shell variable CDPATH defines the search path forthe directory containingarg. Alternative directory names are separated bya colon(:). The default path is<null> (specifying the current directory).Note that the current directory is specified by a null path name,which can appear immediately after the equal signor between the colon delimiters anywhere else in the path list.Ifarg begins with a / then the search pathis not used.Otherwise, each directory in the path issearched forarg.

The second form ofcd substitutes the stringnew for the stringold in the current directory name, PWD, and tries to change to this new directory.

By default, symbolic link names are treated literally whenfinding the directory name.This is equivalent to the-L option.The-P option causessymbolic links to be resolved when determining the directory.The last instance of-L or-P on the command linedetermines which method is used.

Thecd command may not be executed by

command [ -pvxV ] name [ arg ... ]
Without the-v or-V options,command executesname with the arguments given byarg. The-p option causesa default path to be searchedrather than the one defined by the value of PATH. Functions will not be searched for when findingname. In addition, ifname refers to a special built-in,none of the special properties associated with the leadingdaggers will be honored.(For example, the predefined aliasredirect='command exec' prevents a script from terminating when an invalidredirection is given.)With the-x option,if command execution would result in a failure becausethere are too many arguments, errno E2BIG, the shell will invoke commandname multiple times with a subset of the arguments on each invocation.Arguments that occur prior to the first word thatexpands to multiple arguments and after the last wordthat expands to multiple arguments will be passed on each invocation.The exit status will be the maximum invocation exit status.With the-v option,command is equivalent to the built-inwhence command described below.The-V option causescommand to act likewhence -v.
† continue [ n ]
Resume the next iteration of the enclosingfor, while, until, orselect loop.Ifn is specified, then resume at then-th enclosing loop.
disown [ job... ]
Causes the shell not to send a HUP signal toeach givenjob, or all active jobs ifjob is omitted,when a login shell terminates.
echo [ arg ... ]
When the firstarg does not begin with a -, andnone of the arguments contain a \,thenecho prints each of its arguments separated by a spaceand terminated by a new-line.Otherwise, the behavior ofecho is system dependentandprint orprintf described below should be used.Seeecho(1)for usage and description.
†† enum [ -i ] type[=(value ...) ]
Creates a declaration command named type that is aninteger type that allows one of the specifed values asenumeration names. If =(value ...) isomitted, then type must be an indexed array variable with atleast two elements and the values are taken from this array variable.If-i is specified the values are case insensitive.
† eval [ arg ... ]
The arguments are read as inputto the shelland the resulting command(s) executed.
† exec [ -c ] [ -a name ] [ arg ... ]
Ifarg is given,the command specified bythe arguments is executed in place of this shellwithout creating a new process.The-c option causes the environment to be cleared before applyingvariable assignments associated with theexec invocation.The-a optioncausesname rather than the firstarg, to becomeargv[0] for the new process.Input/output arguments may appear andaffect the current process.Ifarg is not given,the effect of this command is tomodify file descriptorsas prescribed by the input/output redirection list.In this case,any file descriptor numbers greater than 2 that areopened with this mechanism are closed when invokinganother program.
† exit [ n ]
Causes the shell to exitwith the exit status specified byn. The value will be the least significant 8 bits of the specified status.Ifn is omitted, then the exit status is that of the last command executed.An end-of-file will also cause the shell to exitexcept for ashell which has theignoreeof option (seeset below) turned on.
†† export [ -p ] [ name[=value] ] ...
Ifname is not given,the names and values of each variable withthe export attribute are printed with the valuesquoted in a manner that allows them to be re-input.The-p optioncauses the wordexport to be inserted before each one.Otherwise, the givennames are marked for automaticexport to theenvironment of subsequently-executed commands.
falseDoes nothing, and exits 1. Used withuntil for infinite loops.
fg [ job... ]
This command is only on systems that support job control.Eachjob specified is brought to the foreground and waited for inthe specified order.Otherwise, the current job isbrought into the foreground.SeeJobs for a description of the format ofjob.
getconf [ name [ pathname ] ]
Prints the current value of the configuration parameter given byname. The configuration parameters are defined by the IEEE POSIX 1003.1and IEEE POSIX 1003.2 standards.(Seepathconf(2)andsysconf(2).)Thepathname argument is required for parameters whose value depends onthe location in the file system.If no arguments are given,getconf prints the names and values of the current configurationparameters.The pathname/ is used for each of the parameters that requirespathname.
getopts [ -a name ] optstring vname [ arg ... ]
Checksarg for legal options.Ifarg is omitted,the positional parameters are used.An option argument begins with a+ or a-. An option not beginning with+ or- or the argument-- ends the options.Options beginning with+ are only recognized whenoptstring begins with a+. optstring contains the letters thatgetopts recognizes.If a letter is followed by a:, that option is expected to have an argument.The options can be separated from the argument by blanks.The option-? causesgetopts to generate a usage message on standard error.The-a argument can be used to specify the name to use for theusage message, which defaults to$0.

getoptsplaces the next option letter it finds inside variablevname each time it is invoked.The option letter will be prepended with a+ whenarg begins with a+. The index of the nextarg is stored in OPTIND. The option argument,if any,gets stored in OPTARG.

A leading: inoptstring causesgetopts to store the letter of an invalidoption in OPTARG, and to setvname to? for an unknown option and to: when a required option argument is missing.Otherwise,getopts prints an error message.The exit status is non-zero when there are no more options.

There is no way to specify any of the options:, +, -, ?, [, and]. The option# can only be specified as the first option.

hist [ -e ename ] [ -nlr ] [ first [ last ] ]
hist -s [ old\=new ] [ command ]
In the first form,a range of commands fromfirst tolast is selected from the last HISTSIZE commands that were typed at the terminal.The argumentsfirst andlast may be specified as a number or as a string.A string is used to locate the most recent command starting withthe given string.A negative number is used as an offset to the current command number.If the-l optionis selected,the commands are listed on standard output.Otherwise, the editor programename is invoked on a file containing thesekeyboard commands.Ifename is not supplied, then the value of the variable HISTEDIT is used.If HISTEDIT is not set, then FCEDIT (default/bin/ed) is used as the editor.When editing is complete, the edited command(s)is executed if the changes have been saved.Iflast is not specified,then it will be set tofirst. Iffirst is not specified,the default is the previous commandfor editing and -16 for listing.The option-r reverses the order of the commands andthe option-n suppresses command numbers when listing.In the second form,command is interpreted asfirst described aboveand defaults to the last command executed.The resulting command is executedafter the optional substitutionold=newis performed.
jobs [ -lnp ] [ job ... ]
Lists information about each given job; or all active jobs ifjob is omitted.The-l option lists process ids in addition to the normal information.The-n option only displays jobs that have stopped or exited since lastnotified.The-p option causes only the process group to be listed.SeeJobs for a description of the format ofjob.
kill [ -s signame ] job ...
kill [ -n signum ] job ...
kill -l [ sig ... ]
Sends either the TERM (terminate) signal or thespecified signal to the specified jobs or processes.Signals are either given by number with the-n option or by name with the-s option(as given in<signal.h>, stripped of the prefix ‘‘SIG’’ withthe exception that SIGCLD is named CHLD).For backward compatibility, then ands can be omitted and the number or name placed immediatelyafter the-. If the signal being sent is TERM (terminate) or HUP (hangup),then the job or process will be sent a CONT (continue) signalif it is stopped.The argumentjob can be the process id of a process that is not a member of one of theactive jobs.SeeJobs for a description of the format ofjob. In the third form,kill -l, ifsig is not specified,the signal names are listed.Otherwise, for eachsig that is a name, the corresponding signal number is listed.For eachsig that is a number, the signal name corresponding to theleast significant 8 bits ofsig is listed.
let arg ...
Eacharg is a separatearithmetic expression to be evaluated.SeeArithmetic Evaluation above, for a description of arithmetic expression evaluation.

The exit status is0 if the value of the last expressionis non-zero, and 1 otherwise.

† newgrp [ arg ... ]
Equivalent toexec /bin/newgrp arg ....
print [ -CRenprsv ] [ -u unit] [ -f format ] [ arg ... ]
With no options or with option- or--, eacharg is printedon standard output.The-f option causes the arguments to be printed asdescribed byprintf. In this case, anye, n, r, R options are ignored.Otherwise,unless the-C, -R, -r, or-v are specified, the followingescape conventions will be applied:
\a The alert character (ascii07).
\b The backspace character (ascii010).
\c Causesprint to end without processing more arguments andnot adding a new-line.
\f The formfeed character (ascii014).
\n The new-line character (ascii012).
\r The carriage return character (ascii015).
\t The tab character (ascii011).
\v The vertical tab character (ascii013).
\E The escape character (ascii033).
\\ The backslash character \.
\0x The character defined by the 1, 2, or 3-digit octalstring given by x.
The-R option will print all subsequent arguments and optionsother than-n. The-e causes the above escape conventions to be applied.This is the default behavior.It reverses the effect of an earlier-r. The-p option causes thearguments to be written onto the pipeof the process spawned with|& instead of standard output.The-v option treats eacharg as a variable name and writes the value intheprintf %B format.The-C option treats eacharg as a variable name and writes the value intheprintf %#B format.The-s option causes thearguments to be written onto the history fileinstead of standard output.The-u option can be used to specify a one digitfile descriptor unit numberunit on which theoutput will be placed.The default is 1.If the option-n is used, nonew-line is added to the output.
printf format [ arg ... ]
The argumentsarg are printed on standard outputin accordance with the ANSI-Cformatting rules associated with the format stringformat. If the number of arguments exceeds the number offormat specifications, theformat string is reused to format remaining arguments.The following extensions can also be used:
%b A%b format can be used instead of%s to cause escape sequences in the correspondingarg to be expanded as described inprint.
%B A%B option causes each of the arguments to be treatedas variable names and the binary value of variablewill be printed.The alternate flag# causes a compound variable to be output on a single line.This is most useful for compound variables and variables whose attributeis-b.
%H A%H format can be used instead of%s to cause characters inarg that are special in HTML and XMLto be output as their entity name.
%P A%P format can be used instead of%s to causearg to be interpreted as an extended regularexpression and be printed as a shell pattern.
%R A%R format can be used instead of%s to causearg to be interpreted as a shell patternand to be printed as an extended regular expression.
%q A%q format can be used instead of%s to cause the resulting string to be quoted in a manner than canbe reinput to the shell.
A%(date-format)T format can be use to treat an argument as a date/time stringand to format the date/time according to thedate-format as defined for thedate(1)command.
%Z A%Z format will output a byte whose value is 0.
%d The precision field of the%d format can be followed by a. and the output base.In this case, the# flag character causesbase# to be prepended.
# The# flag when used with thed specifier without an output base,causes the output to be displayed in thousands units with one of the suffixesk M G T P E to indicate the unit.The# flag when used with thei specifier causes the output to be displayed in 1024 with one of the suffixesKi Mi Gi Ti Pi Ei to indicate the unit.
= The= flag has been added to center the output within the specified field width.
pwd [ -LP ]
Outputs the value of the current workingdirectory.The-L option is the default; it prints the logical name of the current directory.If the-P option is given,all symbolic links are resolved from the name.The last instance of-L or-P on the command linedetermines which method is used.
read [ -ACprsv ] [ -d delim] [ -n n] [ [ -N n] [ [ -t timeout] [ -u unit] [ vname?prompt ] [ vname ... ]
The shell input mechanism.One line is read andis broken up into fields using the characters in IFS as separators.The escape character,\, is used to remove any special meaning for the nextcharacter and for line continuation.The-d optioncauses the read to continue to the first character ofdelim rather than new-line.The-n option causes at mostn bytes to read rather a full linebut will return when reading from a slow deviceas soon as any characters have been read.The-N option causes exactlyn to be read unless an end-of-file has been encountered orthe read times out because of the-t option.In raw mode,-r, the\ character is not treated specially.The firstfield is assigned to the firstvname, the second fieldto the secondvname, etc., with leftover fields assigned to the lastvname. Whenvname has the binary attribute and-n or-N is specified, the bytes that are read are stored directlyinto the variable.If the-v is specified, then the value of the firstvname will be used as a default value when reading from a terminal device.The-A option causes the variablevname to be unset and each field that is read to be stored insuccessive elements of the indexed arrayvname. The-C option causes the variablevname to be read as a compound variable. Blanks will be ignored whenfinding the beginning open parenthesis.The-p option causes the input lineto be taken from the input pipeof a process spawned by the shellusing|&. If the-s option is present,the input will be saved as a command in the history file.The option-u can be used to specify a one digit filedescriptor unitunit to read from.The file descriptor can be opened with theexec special built-in command.The default value of unitn is 0.The option-t is used to specify a timeout inseconds when reading from a terminal or pipe.Ifvname is omitted, then REPLY is used as the defaultvname. An end-of-file with the-p option causes cleanup for this processso that another can be spawned.If the first argument contains a?, the remainder of this word is used as aprompt on standard errorwhen the shell is interactive.The exit status is 0 unless an end-of-file is encounteredorread has timed out.
†† readonly [ -p ] [ vname[=value] ] ...
Ifvname is not given,the names and values of each variable withthe readonly attribute is printed with the valuesquoted in a manner that allows them to be re-inputted.The-p optioncauses the wordreadonly to be inserted before each one.Otherwise, the givenvnames are markedreadonly and thesenames cannot be changedby subsequent assignment.When defining a type, if the value of a readonly sub-variable is not definedthe value is required when creating each instance.
† return [ n ]
Causes a shellfunction or.script to returnto the invoking scriptwith the exit status specified byn. The value will be the least significant 8 bits of the specified status.Ifn is omitted, then the return status is that of the last command executed.Ifreturn is invoked while not in afunction or a.script,then it behaves the same asexit.
† set [ ±BCGabefhkmnoprstuvx ] [ ±o [ option ] ] ... [ ±A vname ] [ arg ... ]
The options for this command have meaning as follows:
-A Array assignment.Unset the variablevname and assign values sequentially from thearg list.If+A is used, the variablevname is not unset first.
-B Enable brace pattern field generation.This is the default behavior.
-B Enable brace group expansion. On by default.
-C Prevents redirection> from truncating existing files.Files that are created are opened with the O_EXCL mode.Requires>| to truncate a file when turned on.
-G Causes the pattern** by itself to match files and zero or more directories and sub-directorieswhen used for file name generation.If followed by a/ only directories and sub-directories are matched.
-a All subsequent variables that are defined are automatically exported.
-b Prints job completion messages as soon as a background job changesstate rather than waiting for the next prompt.
-e Unless contained in a|| or&& command, or the command following anif while oruntil command or in the pipeline following!, if a command has a non-zero exit status,execute the ERR trap, if set,and exit.This mode is disabled while reading profiles.
-f Disables file name generation.
-h Each commandbecomes a tracked alias when first encountered.
-k (Obsolete). All variable assignment arguments are placed in the environment for a command,not just those that precede the command name.
-m Background jobs will run in a separate process groupand a line will print upon completion.The exit status of background jobs is reported in a completion message.On systems with job control,this option is turned on automatically forinteractive shells.
-n Read commands and check them for syntax errors, but do not execute them.Ignored for interactive shells.
-o The following argument can be one of the following option names:
Same as-a.
errexit Same as-e.
bgnice All background jobs are run at a lower priority.This is the default mode.
Same as-B.
emacs Puts you in anemacs style in-line editor for command entry.
globstar Same as-G.
gmacs Puts you in agmacs style in-line editor for command entry.
The shell will not exit on end-of-file.The commandexit must be used.
keyword Same as-k.
markdirs All directory names resulting from file name generation have a trailing/ appended.
monitor Same as-m.
The built-in editors will use multiple lines on the screen for linesthat are longer than the width of the screen. This may not workfor all terminals.
Same as-C.
noexec Same as-n.
noglob Same as-f.
nolog Do not save function definitions in the history file.
notify Same as-b.
nounset Same as-u.
pipefail A pipeline will not complete until all componentsof the pipeline have completed, and the return valuewill be the value of the last non-zero commandto fail or zero if no command has failed.
showme When enabled, simple commands or pipelines preceded by a semicolon(;) will be displayed as if thextrace option were enabled but will not be executed.Otherwise, the leading; will be ignored.
Same as-p.
verbose Same as-v.
trackall Same as-h.
vi Puts you in insert mode of avi style in-line editoruntil you hit the escape character033. This puts you in control mode.A return sends the line.
viraw Each character is processed as it is typedinvi mode.
xtrace Same as-x.
If no option name is supplied, then the current option settings are printed.
-p Disables processing of the$HOME/.profile file and uses the file/etc/suid_profile instead of the ENV file.This mode is on whenever the effective uid (gid)is not equal to the real uid (gid).Turning this off causes the effective uid and gid to beset to the real uid and gid.
-r Enables the restricted shell. This option cannot be unsetonce set.
-s Sort the positional parameters lexicographically.
-t (Obsolete). Exit after reading and executing one command.
-u Treat unset parameters as an error when substituting.
-v Print shell input lines as they are read.
-x Print commands and their arguments as they are executed.
-- Do not change any of the options; useful in setting$1 to a value beginning with-. If no arguments follow this option then the positional parameters are unset.
As an obsolete feature,if the firstarg is- then the-x and-v options are turned off and the nextarg is treated as the first argument.Using+ rather than- causes these options to be turned off.These options can also be used upon invocation of the shell.The current set of options may be found in$-. Unless-A is specified,the remaining arguments are positionalparameters and are assigned, in order, to$1 $2 ....If no arguments are given, then the names and valuesof all variables are printed on the standard output.
† shift [ n ]
The positional parameters from$n+1...are renamed$1 ..., defaultn is 1.The parametern can be any arithmetic expression that evaluates to a non-negativenumber less than or equal to$#.
sleep seconds
Suspends execution for the number of decimal seconds or fractions of asecond given byseconds.
† trap [ -p ] [ action ] [ sig ] ...
The-p option causes the trapaction associated with each trap as specified by the argumentsto be printed with appropriate quoting.Otherwise,action will be processed as if it were an argument toeval when the shellreceives signal(s)sig. Eachsig can be given as a number or as the name of the signal.Trap commands are executed in order of signal number.Any attempt to set a trap on a signal thatwas ignored on entry to the current shellis ineffective.Ifaction is omitted and the firstsig is a number, or ifaction is-, then the trap(s) for eachsig are resetto their original values.Ifaction is the nullstring then this signal is ignored by the shell and by the commandsit invokes.Ifsig is ERR thenaction will be executed whenever a command has a non-zero exit status.Ifsig is DEBUG thenaction will be executed before each command.The variable.sh.command will contain the contents of the current command linewhenaction is running.If the exit status of the trap is2 the command will not be executed.If the exit status of the trap is255 and inside a function or a dot script,the function or dot script will return.Ifsig is0 or EXIT and thetrap statement is executed inside the body of a function defined with thefunction name syntax,then the commandaction is executedafter the function completes.Ifsig is0 or EXIT for atrap set outside any functionthen the commandaction is executedon exit from the shell.Ifsig is KEYBD, thenaction will be executed whenever a key is readwhile inemacs, gmacs, orvi mode.Thetrap commandwith no arguments prints a listof commands associated with each signal number.
Anexit orreturn without an argument in a trap action willpreserve the exit status of the command that invoked the trap.
trueDoes nothing, and exits 0. Used withwhile for infinite loops.
trueDoes nothing, and exits 0. Used withwhile for infinite loops.
†† typeset [ ±ACHSflbnprtux ] [ ±EFLRXZi[n] ] [ -T tname=(assign_list) ] [ -h str ] [ -a [type] ] [ vname[=value ] ] ...
Sets attributes and values for shell variables and functions.When invoked inside a function defined with thefunction name syntax,a new instance of the variablevname is created,and the variable’s value and type are restoredwhen the function completes.The following list of attributes may be specified:
-A Declaresvname to be an associative array.Subscripts are strings rather than arithmeticexpressions.
-C causes eachvname to be a compound variable.value names a compound variable it is copied intovname. Otherwise, it unsets eachvname.
-a Declaresvname to be an indexed array.Iftype is specified, it must be the name of an enumerationtype created with theenum command and it allows enumeration constants to be usedas subscripts.
-E Declaresvname to be a double precision floating point number.Ifn is non-zero, it defines the number of significant figuresthat are used when expandingvname. Otherwise, ten significant figures will be used.
-F Declaresvname to be a double precision floating point number.Ifn is non-zero, it defines the number of places after thedecimal point that are used when expandingvname. Otherwise ten places after the decimal point will be used.
-H This option provides UNIX to host-name file mapping on non-UNIXmachines.
-L Left justify and remove leading blanks fromvalue. Ifn is non-zero, it defines the widthof the field,otherwise it is determined by the width of the value offirst assignment.When the variable is assigned to, it isfilled on the right with blanks or truncated, if necessary, tofit into the field.The-R option is turned off.
-R Right justify and fill with leading blanks.Ifn is non-zero, it defines the widthof the field,otherwise it is determined by the width of the value offirst assignment.The field is left filled with blanks ortruncated from the end if thevariable is reassigned.The-L option is turned off.
-S When used within theassign_list of a type definition, it causes the specified sub-variableto be shared by all instances of the type.When used inside a function defined with thefunction reserved word, the specified variables will havefunction static scope.Otherwise, the variable is unset prior to processing the assignment list.
-T Creates a type named by tname using the compoundassignmentassign_list to tname.
-X Declaresvname to be a double precision floating point numberand expands using the%a format of ISO-C99.Ifn is non-zero, it defines the number of hex digits afterthe radix point that is used when expandingvname. The default is 10.
-Z Right justify and fill with leading zeros ifthe first non-blank character is a digit and the-L option has not been set.Remove leading zeros if the-L option is also set.Ifn is non-zero, it defines the widthof the field,otherwise it is determined by the width of the value offirst assignment.
-f The names refer to function names rather thanvariable names.No assignments can be made and the only othervalid options are-t, -u and-x. The-t optionturns on execution tracing for this function.The-u optioncauses this function to be marked undefined.The FPATH variable will be searched to find the function definitionwhen the function is referenced.If no options other than-f is specified, then the function definition will be displayedon standard output. If+f is specified, then a line containing the function name followedby a shell comment containing the line number and path name of thefile where this function was defined, if any, is displayed.
-b The variable can hold any number of bytes of data.The data can be text or binary.The value is represented by the base64 encoding of the data.If-Z is also specified, the size in bytes of thedata in the buffer will be determined by the size associated with the-Z. If the base64 string assigned results in more data, it will betruncated. Otherwise, it will be filled with byteswhose value is zero.Theprintf format%B can be used to output the actual data in this buffer insteadof the base64 encoding of the data.
-h Used within type definitions to add information when generatinginformation about the sub-variable on the man page.It is ignored when used outside of a type definition.When used with-f the information is associated with the corresponding disciplinefunction.
-i Declaresvname to be represented internally as integer.The right hand side of an assignment is evaluated as anarithmetic expression when assigning to an integer.Ifn is non-zero, it defines the output arithmetic base,otherwise the output base will be ten.
-l All upper-case characters areconverted to lower-case.The upper-case option,-u, is turned off.
-n Declaresvname to be a reference to the variable whose name isdefined by the value of variablevname. This is usually used to reference a variable insidea function whose name has been passed as an argument.
-p The name, attributes and values for the givenvnames are written on standard output in a form that can beused as shell input.If+p is specified, then the values are not displayed.
-r The givenvnames are markedreadonly and thesenames cannot be changedby subsequent assignment.
-t Tags the variables.Tags are user definable and have no specialmeaning to the shell.
-u All lower-case characters are convertedto upper-case.The lower-case option,-l, is turned off.
-x The givenvnames are marked for automaticexport to theenvironment of subsequently-executed commands.Variables whose names contain a .cannot be exported.
The-i attribute cannot be specified along with-R, -L, -Z, or-f.

Using+ rather than- causes these options to be turned off.If novname arguments are given,a list ofvnames (and optionally thevalues) of thevariables is printed.(Using+ rather than- keeps thevalues from being printed.)The-p option causestypeset followed by the option lettersto be printed before each namerather than the names of the options.If any option other than-p is given,only those variableswhich have all of the givenoptions are printed.Otherwise, thevnames andattributes of allvariables that have attributesare printed.

ulimit [ -HSacdfmnpstv ] [ limit ]
Set or display a resource limit.The available resource limits are listed below.Many systems do not support one or more of these limits.The limit for a specified resource is set whenlimit is specified.The value oflimit can be a number in the unit specified below with each resource,or the valueunlimited. The-H and-S options specify whether the hard limit or thesoft limit for the given resource is set.A hard limit cannot be increased once it is set. A softlimit can be increased up to the value of the hard limit.If neither theH norS option is specified, the limit applies to both.The current resource limit is printed whenlimit is omitted.In this case, the soft limit is printed unlessH is specified.When more than one resource is specified, then the limitname and unit is printed before the value.
-a Lists all of the current resource limits.
-c The number of 512-byte blocks on the size of core dumps.
-d The number of K-bytes on the size of the data area.
-f The number of 512-byte blocks on files that can be written by thecurrent process or by child processes (files of any size may be read).
-m The number of K-bytes on the size of physical memory.
-n The number of file descriptors plus 1.
-p The number of 512-byte blocks for pipe buffering.
-s The number of K-bytes on the size of the stack area.
-t The number of CPU seconds to be used by each process.
-v The number of K-bytes for virtual memory.
If no option is given,-f is assumed.
umask [ -S ] [ mask ]
The user file-creation mask is set tomask (seeumask(2)).mask can either be an octal number ora symbolic value as described inchmod(1).If a symbolic value is given,the newumask value is the complement of the result ofapplyingmask to the complement of the previous umask value.Ifmask is omitted, the current value of the mask is printed.The-S option causes the mode to be printed as a symbolicvalue. Otherwise, themask is printed in octal.
† unalias [ -a ] name ...
The aliasesgiven by the list ofnames are removed from the alias list.The-a option causes all thealiases to be unset.
†unset [ -fnv ] vname ...
The variables given by the list ofvnames are unassigned,i.e.,except for sub-variables within a type,their values and attributes are erased.For sub-variables of a type, the values are reset to thedefault value from the type definition.Readonly variables cannot be unset.If the-f optionis set, then the names refer tofunction names.If the-v option is set, then the names refer tovariable names.The-f option overrides-v. If-n is set andname is a name reference, thenname will be unset rather than the variablethat it references.The default is equivalent to-v. Unsetting LINENO, MAILCHECK, OPTARG, OPTIND, RANDOM, SECONDS, TMOUT, and _ removes their special meaning even if they aresubsequently assigned to.
wait [ job ... ]
Wait for the specifiedjob andreport its termination status.Ifjob is not given, then all currently active child processes are waited for.The exit status from this command is that ofthe last process waited for ifjob is specified; otherwise it is zero.SeeJobs for a description of the format ofjob.
whence [ -afpv ] name ...
For eachname, indicate how itwould be interpreted if used as a command name.

The-v optionproduces a more verbose report.The-f option skips the search for functions.The-p optiondoes a path search forname even if name is an alias, a function, or a reserved word.The-p option turns off the-v option.The-a optionis similar to the-v option but causesall interpretations of the given name to be reported.


If the shell is invoked byexec(2),and the first character of argument zero($0) is-, then the shell is assumed to be alogin shell andcommands are read from/etc/profile and then from either.profile in the current directory or$HOME/.profile, if either file exists.Next, for interactive shells, commands are read fromthe file named byperforming parameter expansion, command substitution,and arithmetic substitution onthe value of the environment variable ENV if the file exists.If the-s option is not present andarg and a file by the name ofarg exists, then it reads and executes this script.Otherwise, if the firstarg does not contain a/, a path search is performed on the firstarg to determine the name of the script to execute.The scriptarg must have execute permission and anysetuid andsetgid settings will be ignored.If the script is not found on the path,arg is processed as if it named a built-in command or function.Commands are then read as described below;the following options are interpreted by the shellwhen it is invoked:

-D Do not execute the script, but output the set of double quoted stringspreceded by a$. These strings are needed for localization of the script to different locales.
-E Reads the file named by theENV variable or by$HOME/.kshrcif not defined after the profiles.
-c If the-c option is present, thencommands are read from the firstarg. Any remaining arguments becomepositional parameters starting at0.
-s If the-s option is present or if noarguments remain,then commands are read from the standard input.Shell output,except for the output of theSpecial Commands listed above,is written tofile descriptor 2.
-i If the-i option is present orif the shell input and output are attached to a terminal (as told bytcgetattr(2)),then this shell isinteractive. In this case TERM is ignored (so that kill 0does not kill an interactive shell) and INTR is caught and ignored(so thatwait is interruptible).In all cases, QUIT is ignored by the shell.
-r If the-r option is present, the shell is a restricted shell.
-D A list of all double quoted strings that are preceded by a$ will be printed on standard output and the shell will exit.This set of strings will be subject to language translationwhen the locale is not C or POSIX.No commands will be executed.
-P If-P or-o profile is present, the shell is a profile shell (seepfexec(1)).
-R filename The-R filename option is usedto generate a cross reference databasethat can be used by a separate utilityto find definitions and references for variables and commands.The filename argument specifies the generated database. A script file must beprovided on the command line as well.

The remaining options and arguments are described under theset command above.An optional- as the first argument is ignored.



Rksh93 is used to set up login names and execution environments whosecapabilities are more controlled than those of the standard shell.The actions of

are identical to those of

except that the following are disallowed:

Unsetting the restricted option.
changing directory (seecd(1)),
setting or unsetting the value or attributes of SHELL, ENV, FPATH, or PATH,
specifying path orcommand names containing/,
redirecting output(>, >|, <>, and>>).
adding or deleting built-in commands.
usingcommand -p to invoke a command.

The restrictions above are enforcedafter .profile and the ENV files are interpreted.

When a command to be executed is found to be a shell procedure,invokessh invokesksh invokesksh93 to execute it.Thus, it is possible to provide to the end-user shell proceduresthat have access to the full power ofthe standard shell,while imposing a limited menu of commands;this scheme assumes that the end-user does not have write andexecute permissions in the same directory.

The net effect of these rules is that the writer of the.profile has complete control over user actions,by performing guaranteed setup actionsand leaving the user in an appropriate directory(probablynot the login directory).

The system administrator often sets up a directoryof commands(e.g.,/usr/rbin) that can be safely invoked by

Errors detected by the shell, such as syntax errors,cause the shellto return a non-zero exit status.If the shell is being used non-interactively,then execution of the shell file is abandonedunless the error occurs inside a subshell in which casethe subshell is abandoned.Otherwise, the shell returns the exit status ofthe last command executed (see also theexit command above).Run time errors detected by the shell are reported byprinting the command or function name and the error condition.If the line number that the error occurred on is greater than one,then the line number is also printed in square brackets([]) after the command or function name.

The system wide initialization file, executed for login shells.
The system wide startup file, executed for interactive shells.
The personal initialization file, executed for login shells after /etc/profile.
Default personal initialization file, executed for interactive shells when ENV is not set.
Alternative initialization file, executed when instead of personal initialization file when the real and effective user or group id do not match.
NULL device


    Morris I. Bolsky and David G. Korn,The New KornShell Command and Programming Language, Prentice Hall, 1995.

    POSIX - Part 2: Shell and Utilities, IEEE Std 1003.2-1992, ISO/IEC 9945-2, IEEE, 1993.

    If a commandis executed, and then a command with the same name isinstalled in a directory in the search path before the directory where theoriginal command was found, the shell will continue toexec the original command.Use the-t option of thealias command to correct this situation.

    Some very old shell scripts contain a^ as a synonym for the pipe character|.

    Using thehist built-in command within a compound command will cause the wholecommand to disappear from the history file.

    The built-in command . filereads the whole file before any commands are executed.Therefore,alias andunalias commands in the filewill not apply to any commands defined in the file.

    Traps are not processed while a job is waiting for a foreground process.Thus, a trap onCHLD won’t be executed until the foreground job terminates.

    It is a good idea to leave a space after the comma operator inarithmetic expressions to prevent the comma from being interpretedas the decimal point character in certain locales.


    (Video) Different Shells In Linux | Bash vs C Shell vs Korn Shell | Linux Certification Training | Edureka


    What is the use of ksh command in Unix? ›

    The ksh command invokes the Korn shell, which is an interactive command interpreter and a command programming language. The shell carries out commands either interactively from a terminal keyboard or from a file.

    What is Linux ksh command? ›

    Description. ksh is a command and programming language that executes commands read from a terminal or a file. rksh is a restricted version of the command interpreter ksh; it is used to set up login names and execution environments whose capabilities are more controlled than those of the standard shell.

    How do I run a ksh script in Unix? ›

    1 Answer
    1. make sure that ksh is correctly installed in /bin/ksh. ...
    2. for executing a script run from the command-line ./script in the directory where script exist.
    3. If you want to execut the script from any directory without ./ prefix, you have to add the path to your script to the PATH environment variable, add this line.
    May 24, 2013

    What is Korn shell in Linux? ›

    The Korn shell is an interactive command interpreter and command programming language. It conforms to the Portable Operating System Interface for Computer Environments (POSIX), an international standard for operating systems.

    What is a ksh file? ›

    Script written for the Unix operating system; contains a list of commands that can be run within a Korn Shell or Bourne-Again Shell; can be viewed and edited with a text editor.

    Is ksh still used? ›

    There are various versions of the Korn shell released till now like ksh88, ksh93, etc in order to compensate for the limitations of the older Korn shell. Since it contains various features like associative arrays, dealing with loops, print command, etc, it is still used widely especially by the old Linux/ Unix lovers.

    How do I edit a ksh file in Unix? ›

    NOTE: At least some of these editig commands -- depending on which version of Unix you have -- are the same as those provided by modern Unix systems in the terminal interface.
    Table 2-6. Editing commands in vi input mode.
    CTRL-V"Quote" the next character
    ESCEnter control mode (see below)
    2 more rows

    Who uses Korn shell? ›

    It has been used by many thousands of people at AT&T since 1982, and at many other companies and universities. A survey conducted at one of the largest AT&T Bell Laboratories computer centers showed that 80% of their customers, both programmers and non-programmers, use ksh. ksh is compatible with the Bourne shell.

    How do I write a ksh script? ›

    Let us understand the steps in creating a Shell Script:
    1. Create a file using a vi editor(or any other editor). Name script file with extension . sh.
    2. Start the script with #! /bin/sh.
    3. Write some code.
    4. Save the script file as filename.sh.
    5. For executing the script type bash filename.sh.
    Jun 25, 2022

    How do I run a shell file in Linux? ›

    Steps to execute a shell script in Linux
    1. Create a new file called demo.sh using a text editor such as nano or vi in Linux: nano demo.sh.
    2. Add the following code: ...
    3. Set the script executable permission by running chmod command in Linux: chmod +x demo.sh.
    4. Execute a shell script in Linux: ./demo.sh.
    Aug 11, 2022

    How do I run a script in Linux? ›

    Steps to write and execute a script
    1. Open the terminal. Go to the directory where you want to create your script.
    2. Create a file with . sh extension.
    3. Write the script in the file using an editor.
    4. Make the script executable with command chmod +x <fileName>.
    5. Run the script using ./<fileName>.

    How do you end a ksh script? ›

    ksh. exit will cause the calling shell or shell script to exit with the exit status specified by n . The value will be the least significant 8 bits of the specified status. If n is omitted then the exit status is that of the last command executed.

    Is ksh the same as Bash? ›

    KSH and Bash are somewhat related to each other since KSH encompasses the features of the . sh or Bourne shell, the predecessor of the Bash shell. Both have programmable shells and command processors in Linux and UNIX computer systems. They also carry out commands via a keyboard terminal or from a file.

    How do I start Korn shell? ›

    To begin writing your first Korn shell script, you need to open the vi editor and add the shell name as the first line. After that, you need to build some type of script header telling users who wrote the script, what the script does, and when it was written.

    Is ksh a Linux shell? ›

    KornShell ( ksh ) is a Unix shell which was developed by David Korn at Bell Labs in the early 1980s and announced at USENIX on July 14, 1983. The initial development was based on Bourne shell source code.

    How do you open a ksh shell? ›

    The best way to open an KSH file is to simply double-click it and let the default assoisated application open the file. If you are unable to open the file this way, it may be because you do not have the correct application associated with the extension to view or edit the KSH file.

    How can I update my ksh? ›

    KSH was developed by David Korn at Bell Labs in 1980s.
    Steps to install ksh in Linux
    1. Open the Terminal app.
    2. Type the ' yum install ksh ' command on CentOS/RHEL.
    3. Type the ' dnf install ksh ' command on Fedora Linux.
    4. Update your shell in /etc/passwd.
    5. Start using your ksh shell.
    Apr 1, 2017

    What is difference between sh and ksh? ›

    ksh is korn shell. Sh is bourne shell.

    How do I edit a script in Unix? ›

    Once you know your way around vi, you can edit files on any flavor of UNIX, including Linux.
    To move around the document while in command mode, use the following keys:
    1. h: move one character to the left.
    2. j: move one character down.
    3. k: move one character up.
    4. l: move one character to the right.
    Jul 2, 2003

    How do you edit a shell script? ›

    Editing a line in a text editor
    1. Step 1: Select the line you want to edit. For example, here I've created a fine Shakesperean script:
    2. Step 2: Press ^X^E. Hold down the CTRL key, then press x followed by e. ...
    3. Step 3: Edit the file.
    Mar 25, 2017

    How do I edit a file in Unix? ›

    Edit the file with vim:
    1. Open the file in vim with the command "vim". ...
    2. Type "/" and then the name of the value you would like to edit and press Enter to search for the value in the file. ...
    3. Type "i" to enter insert mode.
    4. Modify the value that you would like to change using the arrow keys on your keyboard.

    Is ksh a programming language? ›

    This is the top level of my "Intro to Korn shell programming" tree. Korn shell is a 'shell-scripting' language, as well as a user-level login shell. It is also a superset of a POSIX.

    What are Korn shell scripts? ›

    The Korn shell is the UNIX shell (command execution program, often called a command interpreter ) that was developed by David Korn of Bell Labs as a comprehensive combined version of other major UNIX shells.

    How can I learn shell scripting? ›

    Top Free Resources to Learn Shell Scripting
    1. Learn Shell [Interactive web portal] ...
    2. Shell Scripting Tutorial [Web portal] ...
    3. Shell Scripting – Udemy (Free video course) ...
    4. Bash Shell Scripting – Udemy (Free video course) ...
    5. Bash Academy [online portal with interactive game] ...
    6. Bash Scripting LinkedIn Learning (Free video course)
    Jun 26, 2020

    How do you start a process in Unix? ›

    Run a Unix process in the background
    1. To run the count program, which will display the process identification number of the job, enter: count &
    2. To check the status of your job, enter: jobs.
    3. To bring a background process to the foreground, enter: fg.
    4. If you have more than one job suspended in the background, enter: fg %#
    Jun 18, 2019

    How do I run a Bash script? ›

    Run Bash Script using the GUI
    1. Open Files and click on the top-right icon.
    2. Select Preferences from the list.
    3. Click the Behavior tab in the menu. Then, select Ask what to do in the Executable Text Files section.
    4. Close the menu and double-click the script file. A prompt appears with several options.
    Dec 9, 2021

    What is UNIX Shell Programming? ›

    A Unix shell is a command-line interpreter or shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting language, and is used by the operating system to control the execution of the system using shell scripts.

    Is a command in Linux? ›

    A Linux command is a program or utility that runs on the command line. A command line is an interface that accepts lines of text and processes them into instructions for your computer. Any graphical user interface (GUI) is just an abstraction of command-line programs.

    Is Linux a command line? ›

    1. Overview. The Linux command line is a text interface to your computer. Often referred to as the shell, terminal, console, prompt or various other names, it can give the appearance of being complex and confusing to use.

    How do I run a file in terminal? ›

    About This Article
    1. Open the Terminal.
    2. Type "cd" followed by the path of the file and press Enter.
    3. Type "sudo chmod +x " to change allow yourself permission to edit the file.
    4. Type "./" to run the file.
    May 10, 2021

    How do I get out of Korn shell? ›

    exit exit from the KornShell
    1. exit [expression]
    2. exit terminates the KornShell. If there is an expression, the value of the expression is the exit status of the shell.
    3. exit returns the value of the arithmetic expression to the parent process as the exit status of the shell.

    How do I stop a script in Linux? ›

    If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard.

    How do I stop a shell script from error? ›

    Stop #bash script on error #linux #zsh
    1. set -e. Sh. Simply place the above code at the top of your script and bash should halt the script in case any of them returns a non-true exit code. ...
    2. set -e -o pipefail. Sh. ...
    3. set +e your_command_goes_here set -e. Sh.
    Nov 16, 2017

    What is difference between sh and ksh? ›

    ksh is korn shell. Sh is bourne shell.

    What is difference between bash and ksh? ›

    Bash stands for Bourne Again Shell which is a clone of Bourne shell. It is licensed under GNU so it is open source and is available for free for the general public whereas KSH stands for Korn shell which was developed by David Korn which merges the features of many shells like Bourne shell, C shell, TC shell, etc.

    How do I write a ksh script? ›

    Let us understand the steps in creating a Shell Script:
    1. Create a file using a vi editor(or any other editor). Name script file with extension . sh.
    2. Start the script with #! /bin/sh.
    3. Write some code.
    4. Save the script file as filename.sh.
    5. For executing the script type bash filename.sh.
    Jun 25, 2022

    How do I edit a ksh file in Unix? ›

    NOTE: At least some of these editig commands -- depending on which version of Unix you have -- are the same as those provided by modern Unix systems in the terminal interface.
    Table 2-6. Editing commands in vi input mode.
    CTRL-V"Quote" the next character
    ESCEnter control mode (see below)
    2 more rows


    1. Shell Scripting Tutorial in Linux
    2. My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency)
    3. Shell Scripting Tutorial | Shell Scripting Crash Course | Linux Certification Training | Edureka
    4. Command Line Arguments with getopts Linux Shell Programming BASH Script Tutorial
    (Kris Occhipinti)
    5. Eval Command - Evaluating Twice Shell Scripting - Tech Arkit
    (Tech Arkit)
    6. Unix & Linux: How to enable ksh command history between sessions? (3 Solutions!!)
    (Roel Van de Paar)
    Top Articles
    Latest Posts
    Article information

    Author: Ray Christiansen

    Last Updated: 01/06/2023

    Views: 6144

    Rating: 4.9 / 5 (49 voted)

    Reviews: 80% of readers found this page helpful

    Author information

    Name: Ray Christiansen

    Birthday: 1998-05-04

    Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

    Phone: +337636892828

    Job: Lead Hospitality Designer

    Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

    Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.