SH_CSH_KSH

125
SH_CSH_KSH Linux and Unix sh command Quick links About sh Syntax Examples Related commands Linux and Unix main page About sh sh is the command name of the Bourne shell, the standard command languageinterpreter of Unix and many Unix-like operating systems, including Linux. Syntax sh [-acefhikmnprstuvx] [arg] ... Description And History sh is a command language interpreter that executes commands read from a command line string, the standard input, or a specified file. The Bourne shell was developed in 1977 by Stephen Bourne at AT&T's Bell Labs in 1977. It was the default shell of Unix Version 7. Most Unix-like systems contain the file /bin/sh which is either the Bourne shell, or a symbolic link (or hard link) to a compatible shell. The Bourne Shell was originally developed as a replacement for the Thompson shell, whose executable file was also named sh. Although it is used as an interactive command interpreter, its original purpose was to function as a scripting language. Features of the Bourne Shell include: scripts can be invoked as commands by using their filename the shell may be used interactively or non-interactively commands may be executed synchronously or asynchronously

Transcript of SH_CSH_KSH

SH_CSH_KSH Linux and Unix sh command Quick links

About sh Syntax Examples Related commands Linux and Unix main page

About sh

sh is the command name of the Bourne shell, the standard command

languageinterpreter of Unix and many Unix-like operating systems,

including Linux.

Syntax

sh [-acefhikmnprstuvx] [arg] ...

Description And History

sh is a command language interpreter that executes commands read from

a command line string, the standard input, or a specified file.

The Bourne shell was developed in 1977 by Stephen Bourne at AT&T's Bell

Labs in 1977. It was the default shell of Unix Version 7. Most Unix-like systems

contain the file /bin/sh which is either the Bourne shell, or a symbolic

link (or hard link) to a compatible shell.

The Bourne Shell was originally developed as a replacement for

the Thompson shell, whose executable file was also named sh. Although it is

used as an interactive command interpreter, its original purpose was to function

as a scripting language.

Features of the Bourne Shell include: • scripts can be invoked as commands by using their filename • the shell may be used interactively or non-interactively • commands may be executed synchronously or asynchronously

• the shell supports input and output redirection, and pipelines • a robust set of built-in commands • flow control constructs, quotation facilities, and functions • typeless variables • both local and global variable scopes • scripts can be interpreted, i.e., they do not have to be compiled to be executed • Command substitution using back quotes, e.g.: `command` • "Here documents": the use of << to embed a block of input text within a script • "for/do/done" loops, in particular the use of $* to loop over arguments • "case/in/esac" selection mechanism, primarily intended to

assist argument parsing • support for environment variables using keyword parameters and exportable

variables • strong provisions for controlling input and output and in its expression-matching

facilities.

Use of the Bourne Shell has largely been suerceded by the Bourne-Again Shell

(bash), which supports more user-friendly interactive features such as job

control and acommand history.

Commands

A simple-command is a sequence of non-blank words separated by blanks (a

blank is a tab or a space). The first word specifies the name of the command to

be executed. Except as specified below, the remaining words are passed as

arguments to the invoked command. The command name is passed as argument

0 (see exec). The value of a simple-command is its exit status if it terminates

normally or 200+status if it terminates abnormally (see our signals page for a

list of status values).

A pipeline is a sequence of one or more commands separated by a vertical bar

("|"). The standard output of each command but the last is connected by

a pipe to thestandard input of the next command. Each command is run as a

separate process; the shell waits for the last command to terminate. The value

of a pipeline is the exit status of its last command.

A list is a sequence of one or more pipelines separated by ";", "&", "&&" or "||"

and optionally terminated by ";" or "&". ";" and "&" have equal precedence

which is lower than that of "&&" and "||", "&&" and "||" also have equal

precedence. A semicolon causes sequential execution; an ampersand causes the

preceding pipeline to be executed without waiting for it to finish. The symbol

"&&" ("||") causes the list following to be executed only if the preceding pipeline

returns a zero (non zero) value.Newlines may appear in a list, instead of

semicolons, to delimit commands.

A "#" at the beginning of a word starts a comment and causes the rest of the

line to be ignored.

A command is either a simple-command or one of the following. The value

returned by a command is that of the last simple-command executed in the

command:

for name [inword ...] dolist done For loop. Each time a for command is executed, name is set to the next word in thefor word list. If 'in word ...' is omitted, then 'in "$@"' is assumed. Execution ends when there are no more words in the list.

case word in[pattern [|pattern ] ... )list ;;] ...esac

A case command executes the list associated with the first pattern that matchesword. The form of the patterns is the same as that used for file name generation.

if list thenlist [elif listthen list] ... [else list] fi

The list following if is executed, and if it returns zero, the list following then is executed. Otherwise, the list following elif ("else if") is executed and if its value is zero, the list following then is executed. Failing that the else list is executed.

while list [dolist] done A while command repeatedly executes the while list, and if its value is zero, executes the do list; otherwise the loop terminates. The value returned by a whilecommand is that of the last executed command in the do list. until may be used in place of while to negate the loop termination test.

( list ) Execute list in a subshell.

{ list; } list is simply executed.

name() {list; } Defines the shell function name. Each time name is recognized as a command, listis executed, with the positional parameters $1, $2... set to the arguments of the command. After the function returns, the previous positional parameters are restored.

The following words are only recognized as the first word of a command, and

when not enclosed in quotes: • if • then

• else • elif • fi • case • in • esac • for • while • until • do • done • { • }

Command Substitution

The standard output from a command enclosed in a pair of grave accents (``)

may be used as part or all of a word; trailing newlines are removed. For

example, if the executable script echotest.sh contained the command: echo "The name of this script is `basename $0`."

Then running the script would display the combined output

of echo and basename: The name of this script is echotest.sh.

Parameter Substitution

The character $ is used to introduce substitutable parameters. Positional

parameters may be assigned values by set. Variables may be set in the form

"name=value [name=value ] ...".

${parameter} A parameter is a sequence of letters, digits or underscores (a name), a digit, or any of the characters * @ # ? - $ !. The value, if any, of the parameter is substituted. The braces are required only when parameter is followed by a letter, digit, or underscore that is not to be interpreted as part of its name. If parameter is a digit then it is a positional parameter. If parameter is * or@ then all the positional parameters, starting with $1, are substituted separated by spaces. $0 is set from argument zero when the shell is invoked.

${parameter:-word} If parameter is set and not empty then substitute its value; otherwise substitute word.

${parameter:=word} If parameter is not set and not empty then set it to word; the value of the parameter is then substituted. Positional parameters may not be assigned-to in this way.

${parameter:?word} If parameter is set and not empty then substitute its value; otherwise, printword and exit from the shell. If word is omitted then a standard message is printed.

${parameter:+word} If parameter is set and not empty then substitute word; otherwise substitute nothing.

If the : is omitted, the substitutions are only executed if the parameter is set,

even if it is empty.

In the above, word is not evaluated unless it is to be used as the substituted

string. (So, for example, "echo ${d-`pwd`}" will only execute pwd if d is

unset.)

The following parameters are automatically set by the shell:

# The number of positional parameters, in decimal.

- Options supplied to the shell on invocation or by set.

? The value returned by the last executed command, in decimal.

$ The process number of this shell.

! The process number of the last background command invoked.

The following parameters are used by the shell:

CDPATH The search path for the cd command.

HOME The default argument (home directory) for the cd command.

OPTARG The value of the last option argument processed by the getopts special command.

OPTIND The index of the last option processed by the getopts special command.

PATH The search path for commands (see Execution).

MAIL If this variable is set to the name of a mail file then the shell informs the user of the arrival of mail in the specified file.

MAILCHECK If this variable is set, it is interpreted as a value in seconds to wait between checks for new mail. The default is 600 (10 minutes). If the value is zero, mail is checked before each prompt.

MAILPATH A colon-separated list of files that are checked for new mail. MAIL is ignored if this variable is set.

PS1 Primary prompt string, by default '$ '.

PS2 Secondary prompt string, by default '> '.

IFS Internal field separators, normally space, tab, and newline.

LANG,LC_ALL Locale variables.

LC_CTYPE Affects the mapping of bytes to characters for file name generation, for the interpretation of '\', and for handling $IFS.

SHACCT If this variable is set in the initial environment passed to the shell and points to a file writable by the user, accounting statistics are written to it.

TIMEOUT The shell exists when prompting for input if no command is entered for more than the given value in seconds. A value of zero means no timeout and is the default.

Blank Interpretation

After parameter and command substitution, any results of substitution are

scanned for internal field separator characters (those found in $IFS) and split

into distinct arguments where such characters are found. Explicit null arguments

("" or '') are retained. Implicit null arguments (those resulting from parameters

that have no values) are removed.

File Name Generation

Following substitution, each command word is scanned for the characters "*",

"?" and "[". If one of these characters appears then the word is regarded as a

pattern. The word is replaced with alphabetically sorted file names that match

the pattern. If no file name is found that matches the pattern then the word is

left unchanged. The character. at the start of a file name or immediately

following a "/", and the character "/", must be matched explicitly.

* Matches any string, including the null string.

? Matches any single character.

[...] Matches any one of the characters enclosed. A pair of characters separated by - matches any character lexically between the pair.

[!...] Matches any character except the enclosed ones.

Quoting

The following characters have a special meaning to the shell and cause

termination of a word unless quoted: • ; • & • ( • ) • | • ^ • < • > • newline • space • tab

A character may be quoted by preceding it with a "\". "\\newline" is ignored. All

characters enclosed between a pair of quote marks (''), except a single quote,

are quoted. Inside double quotes ("") parameter and command substitution

occurs and "\" quotes the characters \, ` " and $.

'$*' is equivalent to '$1 $2 ...', whereas '$@' is equivalent to '"$1" "$2"...'.

Prompting

When used interactively, the shell prompts with the value of $PS1 before

reading a command. If at any time a newline is typed and further input is

needed to complete a command then the secondary prompt ($PS2) is issued.

Input and Output

Before a command is executed its input and output may be redirected using a

special notation interpreted by the shell. The following may appear anywhere in

a simple-command or may precede or follow a command and are not passed on

to the invoked command. Substitution occurs before word or digit is used:

<word Use file word as standard input (file descriptor 0).

>word Use file word as standard output (file descriptor 1). If the file does not exist then it is created; otherwise it is truncated to zero length.

>>word Use file word as standard output. If the file exists then output is appended (by seeking to the end); otherwise the file is created.

<<[-]word

The shell input is read up to a line the same as word, or end of file. The resulting document becomes the standard input. If any character of word is quoted, then no interpretation is placed upon the characters of the document; otherwise, parameter and command substitution occurs, \newline is ignored, and \ is used to quote the characters \ $ ` and the first character of word. The optional "-" causes leading tabulator character to be stripped from the resulting

document; word may then also be prefixed by a tabulator.

<&digit The standard input is duplicated from file descriptor digit. Similarly for the standard output using >.

<&- The standard input is closed. Similarly for the standard output using >.

If one of the above is preceded by a digit then the file descriptor created is that

specified by the digit (instead of the default 0 or 1). For example, "... 2>&1"

creates file descriptor 2 to be a duplicate of file descriptor 1. If a command is

followed by &then the default standard input for the command is the empty file

(/dev/null), unless job control is enabled. Otherwise, the environment for the

execution of a command contains the file descriptors of the invoking shell as

modified by input output specifications.

Environment

The environment is a list of name-value pairs that is passed to an executed

program in the same way as a normal argument list; see exec and environ. The

shell interacts with the environment in several ways. On invocation, the shell

scans the environment and creates a parameter for each name found, giving it

the corresponding value. Executed commands inherit the same environment. If

the user modifies the values of these parameters or creates new ones, none of

these affects the environment unless the export command is used to bind the

shell's parameter to the environment. The environment seen by any executed

command is thus composed of any unmodified name-value pairs originally

inherited by the shell, plus any modifications or additions, all of which must be

noted in export commands.

The environment for any simple-command may be augmented by prefixing it

with one or more assignments to parameters. Thus these two lines are

equivalent: TERM=450 cmd args

(export TERM; TERM=450; cmd args)

Signals

The INTERRUPT and QUIT signals for an invoked command are ignored if the

command is followed by & (unless job control is enabled); otherwise signals

have the values inherited by the shell from its parent. (See also trap.)

Execution

Each time a command is executed the above substitutions are carried out. The

shell then first looks if a function with the command name was defined; if so, it

is chosen for execution. Otherwise, except for the 'special commands' listed

below a new process is created and an attempt is made to execute the command

via an exec.

The shell parameter $PATH defines the search path for the directory containing

the command. Each alternative directory name is separated by a colon (":"). The

default path is '/usr/sbin:/bin:/usr/bin:'. If the command name contains

a / then the search path is not used. Otherwise, each directory in the path is

searched for an executable file. If the file has execute permission but is not

an a.out file, it is assumed to be a file containing shell commands. A subshell

(i.e., a separate process) is spawned to read it. A parenthesized command is

also executed in a subshell.

Special Commands

: No effect; the command does nothing.

. file Read and execute commands from file and return. The search path $PATH is used to find the directory containing file.

break [n] Exit from the enclosing for or while loop, if any. If n is specified then break nlevels.

continue [n] Resume the next iteration of the enclosing for or while loop. If n is specified then resum at the nth enclosing loop.

cd [arg] Change the current directory to arg. The shell paramete $HOME is the default arg. If no directory arg is found an the $CDPATH parameter contains a list of directories separated by colons, each of these directories is used a prefix to arg in the given order, and the current directo is set to the first one that is found. If no suitable directory been found, an interactive shell may try to fix spelling errors and propose an alternative directory name:

cd /usf/lb

cd /usr/lib? y

ok

If the answer is 'y' or anything other than 'n', the shell will set the current directory to the one proposed.

echo [arg ...] Each arg is printed to standard output; afterwards, a newline is printed. The following escape sequences are recognized in arg:

\b Prints a backspace character.

\c Causes the command to return immediately. Any following characters are ignored, and the terminating newline is not printed.

\f Prints a formfeed character.

\n Prints a newline character.

\r Prints a carriage-return character.

\t Prints a tabulator character.

\v Prints a vertical tabulator character.

\\ Prints a backslash character.

\0nnn Prints the character (byte) with octal value nnn.

If /usr/ucb precedes /usr/sbin or /usr/bin in the current setting of the$PATH variable and the first argument is -n, the terminating newline is not printed, and no escape sequences are recognized. If the $SYSV3 variable is set in the initial environment passed to the shell, the -n argument is also interpreted but escape sequences are processed as usual.

eval [arg ...] The arguments are read as input to the shell and the resulting command(s) are executed.

exec [arg ...] The command specified by the arguments is executed in place of this shell without creating a new process. Input/output arguments may appear and (if no other

arguments are given) cause the shell input/output to be modified.

exit [n] Causes the shell to exit with the exit status specified by If n is omitted then the exit status is that of the last command executed. (An end of file will also exit from th shell.)

export [name ...] The given names are marked for automatic export to th environment of subsequently-executed commands. If n arguments are given then a list of exportable names is printed.

getopts optstringvariable [arg ...] Retrieves options and option-arguments from arg (or th positional parameters) similar to getopt. optstring is a list of characters (bytes); each character represents an option letter. A character followed by ":" indicates that the option has an argument. Calling getopts repeatedly causes one option to be retrieved per call. The index of the current option is stored in the variable OPTIND; it initialized to 1 when the shell starts. The option-argument, if any, is stored in the OPTARG variable. Th option character is stored in the variable. When the end of the options is reached, getoptsreturns with a non-ze value. A missing argument or an illegal option also caus a non-zero return value, and an error message is printe to standard error.

hash [name ...] The shell maintains a hash table of the locations of external commands. If name arguments are given, each one is looked up and is inserted into the table if it is found. Otherwise, a list of the commands currently in th table is printed.

newgrp [arg ...] Equivalent to "exec newgrp arg ...".

pwd Prints the name of the present working directory.

read [-r] name ... One line is read from the standard input; successive words of the input are assigned to the variables name i order, with leftover words to the last variable. The retur code is 0 unless end-of-file is encountered. Normally, backslashes escape the following character; this is inhibited if the -r option is given.

readonly [name ...] The given names are marked readonly and the values o the these names may not be changed by subsequent assignment. If no arguments are given then a list of all readonly names is printed.

return [n] Return from a shell function to the execution level abov

With the argumentn, the special variable $? is set to th given value.

set [--aefhknptuvx[arg ...]] -- No effect; useful if the first arg begins with -.

-a

Export any variables that are modified or created from now on.

-e

If non-interactive, exit immediately if a command fails.

-f File name generation is disabled.

-h

When a function is defined, look up all external commands it contains as described for the hash special command. Normally, these commands are looked up when they are executed.

-k

All keyword arguments are placed in the environment for a command, not just those that precede the command name.

-m

Enables job control (see below).

-n

Read commands but do not execute them.

-p

Makes the shell privileged. A privileged shell does not execute the system and user profiles; if an non-privileged shell (the default) has an effective user or group id different to its real user or group id or if it has an effective user or group id below 100, it resets its effective user or group id, respectively, to the corresponding real id at startup.

-t Exit after reading and executing one command.

-u

Treat unset variables as an error when substituting.

-v

Print shell input lines as they are read.

-x

Print commands and their arguments as they are executed.

- Turn off the -x and -v options.

These flags can also be used upon invocation of the she The current set of flags may be found in $-. If + is used instead of -, the given flags are disabled. Remaining arguments are positional parameters and ar assigned, in order, to$1, $2, etc. If no arguments are given then the values of all names are printed.

shift [n] The positional parameters from $2... are renamed $1.. The n argument causes a shift by the given number, i.e. $n+1 is renamed to $1 and so forth.

times Print the accumulated user and system times for processes run from the shell.

test [expr] test evaluates the expression expr, and if its value is tr then it returns zero exit status; otherwise, a non-zero e status is returned. test returns a non-zero exit if there are no arguments. The following primitives are used to construct expr:

-r file true if the file exists and is readable.

-w file true if the file exists and is writable.

-u file true if the file exists and has the setuid bit set.

-g file true if the file exists and has the setgid bit set.

-k file true if the file exists and has the sticky bit set.

-f file true if the file exists and is a regular file (or any file other than a directory if /usr/ucb occurs early in the current $PATHparameter).

-d file true if the file exists and is a directory.

-h file true if the file exists and is a symbolic link.

-L file true if the file exists and is a symbolic link.

-p file true if the file exists and is a named pipe.

-b file true if the file exists and is a block device.

-c file true if the file exists and is a character device.

-s file true if the file exists and has a size greater than zero.

-t[fildes]

true if the open file whose file descriptor number is fildes (1 by default) is associated with a terminal device.

-z s1 true if the length of string s1 is zero.

-n s1 true if the length of the string s1 is nonzero

s1 =s2 true if the strings s1 and s2 are equal.

s1 !=s2 true if the strings s1 and s2 are not equal.

s1 true if s1 is not the null string.

n1 -eqn2

true if the integers n1 and n2 are algebraically equal. Any of the comparisons ne, -gt, -ge, -lt, or -le may be used in place of -eq.

These primaries may be combined with the following operators:

! unary negation operator

-a binary AND operator

-o binary OR operator

( expr ) parentheses for grouping

-a has higher precedence than -o. Notice that all the operators and flags are separate arguments to test. Notice also that parentheses are meaningful as comman separators and must be escaped.

trap [arg] [n|name] ... arg is a command to be read and executed when the sh receives signal(s)n. (Note that arg is scanned once whe the trap is set and once when the trap is taken.) trap commands are executed in order of signal number. If argis absent then all trap(s) n are reset to their original values. If arg is the null string then this

signal is ignored by the shell and by invoked commands If nis 0 then the command arg is executed on exit from the shell, otherwise upon receipt of signal n as numbere in signal. Trap with no arguments prints a list of commands associated with each signal number. A symbolic name can be used instead of the n argument; is formed by the signal name in the Clanguage minus the SIG prefix, e.g. TERM for SIGTERM. EXIT is the same as a zero ('0') argument.

type name ... For each name, prints if it would be executed as a shell function, as a special command, or as an external command. In the last case, the full path name to the command is also printed.

ulimit [-[HS][a|cdfmnstuv]] ulimit [-[HS][c|d|f|m|n|s|t|u|v]] [limit]

Handles resource limits for the shell and processes created by it, as described in getrlimit. Without a limit argument, the current settings are printed; otherwise, a new limit is set. The following options are accepted:

-H

Sets a hard limit. Only the super-user may raise a hard limit.

-S

Sets a soft limit. A soft limit must not exceed the hard limit. If neither -H or -S is given, the soft limit is printed, or both limits are set, respectively.

-a

Chooses all limits described.

-c The maximum size of a core dump in 512-byte blocks.

-d

The maximum size of the data segment in kbytes.

-f The maximum size of a file in 512-byte blocks. This is the default if no limit is explicitly selected.

-l The maximum size of locked memory in kbytes.

-m

The maximum resident set size in kbytes.

-n

The maximum number of open file descriptors.

-s The maximum size of the stack segment in kbytes.

-t The maximum processor time in seconds.

-u

The maximum number of child processes.

-v

The maximum address space size in kbytes.

umask [-S] [nnn] The user file creation mask is set to the octal value nnn (see umask). Symbolic modes as described in chmod are also accepted. If nnn is omitted, the curre value of the mask is printed. With the -S option, the current mask is printed as a symbolic string.

unset variable ... Unsets each variable named.

wait [n] Wait for the specified process and report its termination status. If n is not given then all currently active child processes are waited for. The return code from this command is that of the process waited for. If n does no refer to a child process of the shell, wait returns immediately with code 0.

Invocation

If the first character of argument zero is -, commands are read

from /etc/profile and$HOME/.profile, if the respective file exists. Commands

are then read as described below. The following flags are interpreted by the shell

when it is invoked:

-cstring

If the -c flag is present then commands are read from string.

-s If the -s flag is present or if no arguments remain then commands are read from thestandard input. Shell output is written to file descriptor 2.

-i If the -i flag is present or if the shell input and output are attached to a terminal (as told by the function isatty()) then this shell is interactive. In this case the terminate signalSIGTERM is ignored (so that 'kill 0' does not kill an interactive shell) and the interrupt signal SIGINT is caught and ignored (so that wait is interruptable). In all cases SIGQUITis ignored by the shell.

The remaining flags and arguments are described under the set command.

Job Control

When an interactive shell is invoked as jsh, job control is enabled. Job control

allows to stop and resume processes, and to switch between foreground and

background jobs. A job consists of the commands of a single pipeline. Each job is

placed in a separate process group; a login shell and all jobs created by it form a

session. Interrupt, quit, and other terminal control characters only affect the

current foreground process group. The foreground job can be stopped pressing

the suspend key, typically ^Z; any job can be stopped by sending

the STOP signal to it. Jobs are identified by jod ids of the following form:

%, %%, or %+ The current job.

%- The job that was previously the current job.

?string The only job whose name contains string.

%number The job with the given number.

number The job with process group id number.

string The only job for which string is a prefix of its name.

The following built-in commands are additionally available with job control:

bg [jobid ...] Places each jobid in the background. The default job id is the current job.

fg [jobid ...] Sequentially selects each jobid as the foreground job. The default job id is the current job.

jobs [-p|-l] [jobid...] | [-x command[arguments ...]]

Prints information about each jobid, or executes command:

-l Includes the process group id and the starting directory.

-p Includes the process group id.

-xcommand[arguments...]

Executes command with arguments; each argument that forms a job id is replaced by the process group id of the respective job. It is an error if a given job does not exist.

kill [[-s signal | -signal] jobid ... | -l[status]

A special version of the kill command that recognizes job ids in its arguments.

stop jobid ... Stops the given jobs (i.e. sends a STOP signal to them).

suspend Stops the shell itself. This is not allowed if the shell is a session leader.

wait [jobid] The wait command (see above) recognizes job ids in its arguments.

Notes

For historical reasons, ^ is a synonym for | as pipeline separator. Its use in new

applications is therefore discouraged.

If a command other than a simple-command (i.e. 'for ...', 'case ...', etc.) is

redirected, it is executed in a subshell. If variable assignments must be visible in

the parent shell after the input has been redirected, the exec special command

can be used: exec 5<&0 <input

while read line

do

...

variable=value

...

done

exec <&5 5<&-

If parameters that have been inherited from the initial environment are modified,

they must be explicitly exported to make the change visible to external

commands, as described under 'Environment' above.

The $IFS parameter is applied to any unquoted word. Thus: IFS=X

echoXfoo

executes the 'echo' command with the argument 'foo'. The command 'set --' without further arguments is a no-op (no operation). The shift special command

can be used to delete all positional parameters.

There is only one namespace for both functions and parameters. A function

definition will delete a parameter with the same name and vice-versa.

Parameter assignments that precede a special command affect the shell itself;

parameter assignments that precede the call of a function are ignored.

Files

/etc/profile

$HOME/.profile

/tmp/sh*

/dev/null

Examples

sh

Invokes the Bourne shell, and places you at a command prompt.

Related commands

bc init kill ksh login newgrp ps pwd stty

Linux and Unix csh command Quick links

About csh Syntax Examples Related commands Unix main page

About csh

csh, the C shell, is a command interpreter with a syntax similar to the C

programming language.

Syntax

csh [-bcefimnstVvXx] [argument ...]

csh [-l]

Description

csh is a command language interpreter with many powerful features, including a

history mechanism (see History substitutions), job control facilities (see Jobs),

interactive file name and user name completion (see File Name Completion), and

a C-like syntax. It is used both as an interactive login shell and a shell script

command processor.

If the first argument (argument 0) to the shell is a dash ('-'), then csh is run as

a login shell. A login shell also can be specified by invoking the shell with the -l flag as the only argument.

Options

-b This flag forces a “break” from option processing, causing any further shell arguments to be treated as non-option arguments. The remaining arguments will not be interpreted as shell options. This may be used to pass options to a shell script without confusion or possible subterfuge. The shell will not run a set-user-ID script without this option.

-c Commands are read from the single argument following -c, which must be present. Any remaining arguments are placed in argv.

-e The shell exits if any invoked command terminates abnormally or yields a non-zero exit status.

-f The shell will start faster, because it will neither search for nor execute commands from the file .cshrc in the invoker's home directory. Note that if the environment variable HOME is not set, fast startup is the default.

-i The shell is interactive and prompts for its top-level input, even if it appears not to be a terminal. Shells are interactive without this option if their inputs and outputs are terminals.

-l The shell is a login shell (but only if -l is the only flag specified).

-m

Read .cshrc, regardless of its owner and group. This option is dangerous and should only be used by the superuser.

-n Commands are parsed, but not executed. This is useful for checking the syntax of shell scripts. When used interactively, the shell can be terminated by pressing control-D (end-of-file character), since exit will not work.

-s Command input is taken from the standard input.

-t A single line of input is read and executed. A backslash (\) may be used to escape thenewline at the end of this line and continue onto another line.

-V Causes the verbose variable to be set even before .cshrc is executed.

-v Causes the verbose variable to be set, with the effect that command input is echoed after history substitution.

-X Causes the echo variable to be set even before .cshrc is executed.

-x Causes the echo variable to be set, so that commands are echoed immediately before execution.

After flag arguments are processed, if arguments remain but none of the -c, -i, -s, or -t options were given, the first argument is taken as the name of a file of

commands to be executed. The shell opens this file, and saves its name for

possible resubstitution by $0. Since many systems use either the standard

version 6 or version 7 shells whose shell scripts are not compatible with this

shell, the shell will execute such a “standard” shell if the first character of a

script is not a hash mark (#); i.e., if the script does not start with a comment.

Remaining arguments initialize the variable argv.

An instance of csh begins by executing commands from the

file /etc/csh.cshrc and, if this is a login shell, /etc/csh.login. It then

executes commands from .cshrc in the home directory of the invoker, and, if

this is a login shell, the file .login in the same location. It is typical for users

on CRTs to put the command "stty crt" in their .login file, and to also

invoke tset there.

In the normal case, the shell will begin reading commands from the terminal,

prompting with % . Processing of arguments and the use of the shell to process

files containing command scripts are described below.

The shell repeatedly performs the following actions: a line of command input is

read and broken into “words”. This sequence of words is placed on the command

history list and parsed. Finally each command in the current line is executed.

When a login shell terminates it executes commands from the files .logout in

the user's home directory and /etc/csh.logout.

Lexical Structure

The shell splits input lines into words at blanks and tabs with the following

exceptions. The characters &, |, ;, <, >, (, and ) form separate words. If

doubled in&&, ||, <<, or >>, these pairs form single words. These parser

metacharacters may be made part of other words, or have their special meaning

prevented, by preceding them with a backslash (\). A newline preceded by a \ is

equivalent to a blank.

Strings enclosed in matched pairs of quotations, ', `, or ", form parts of a word;

metacharacters in these strings, including blanks and tabs, do not form separate

words. These quotations have semantics to be described later. Within pairs

of ' or "characters, a newline preceded by a \ gives a true newline character.

When the shell's input is not a terminal, the character # introduces a comment

that continues to the end of the input line. This special meaning is prevented

when preceded by \ and in quotations using `, ', and ".

Commands

A simple command is a sequence of words, the first of which specifies the

command to be executed. A simple command or a sequence of simple

commands separated by |characters forms a pipeline. The output of each

command in a pipeline is connected to the input of the next. Sequences of

pipelines may be separated by ;, and are then executed sequentially. A sequence

of pipelines may be executed without immediately waiting for it to terminate by

following it with a &.

Any of the above may be placed in ( ) to form a simple command (that may be a

component of a pipeline, for example). It is also possible to separate pipelines

with ||or && showing, as in the C language, that the second is to be executed

only if the first fails or succeeds, respectively. (See Expressions.)

Jobs

The shell associates a job with each pipeline. It keeps a table of current jobs,

printed by the jobs command, and assigns them small integer numbers. When a

job is started asynchronously with &, the shell prints a line that looks like: [1] 1234

showing that the job which was started asynchronously was job number 1 and

had one (top-level) process, whose process ID was 1234.

If you are running a job and wish to do something else you may hit ^Z (control-

Z), which sends a SIGSTOP signal to the current job. The shell will then

normally show 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

the bg command, or run some other commands and eventually bring the job

back into the foreground with the fgcommand. A ^Z takes effect immediately

and is like an interrupt in that pending output and unread input are discarded

when it is typed. There is another special key^Y that does not generate

a SIGSTOP signal until a program attempts to read it. This request can usefully

be typed ahead when you have prepared some commands for a job that you

want to stop after it has read them.

A job being run in the background will stop if it tries to read from the terminal.

Background jobs are normally allowed to produce output, but this can be

disabled by giving the command stty tostop. If you set this tty option, then

background jobs will stop when they try to produce output like they do when

they try to read input.

There are several ways to refer to jobs in the shell. The character % introduces

a job name. If you want to refer to job number 1, you can name it as %1. Just

naming a job brings it to the foreground; so, %1 is a synonym for fg %1,

bringing job number 1 back into the foreground. Similarly, saying %1 & resumes job number 1 in the background. Jobs can also be named by prefixes

of the string typed in to start them, if these prefixes are unambiguous;

thus %ex would normally restart a suspended exjob, if there were only one

suspended job whose name began with the string "ex". It is also possible to

say %?string, which specifies a job whose text contains string, if there is only

one such job.

The shell maintains a notion of the current and previous jobs. In output about

jobs, the current job is marked with a + and the previous job with a -. The

abbreviation %+refers to the current job and %- refers to the previous job. For

close analogy with the syntax of the history mechanism (described

below), %% is also a synonym for the current job.

The job control mechanism requires that the stty option new be set. It is an

artifact from a new implementation of the tty driver that allows generation of

interrupt characters from the keyboard to tell jobs to stop. See stty for details on

setting options in the new tty driver.

Status Reporting

The shell learns immediately whenever a process changes state. It normally

informs you whenever a job becomes blocked so that no further progress is

possible, but only just before it prints a prompt. This is done so that it does not

otherwise disturb your work. If, however, you set the shell variable notify, the

shell will notify you immediately of changes of status in background jobs. There

is also a shell commandnotify that marks a single process so that its status

changes will be immediately reported. By default notify marks the current

process; simply say notify after starting a background job to mark it.

When you try to leave the shell while jobs are stopped, you will be warned that

“You have stopped jobs”. You may use the jobs command to see what they are.

If you try to exit again immediately, the shell will not warn you a second time,

and the suspended jobs will be terminated.

File Name Completion

When the file name completion feature is enabled by setting the shell

variable filec(see set), csh will interactively complete file names and user

names from unique prefixes when they are input from the terminal followed by

the escape character (the escape key, or control-[). For example, if the current

directory looks like DSC.OLD bin cmd lib xmpl.c

DSC.NEW chaosnet cmtest mail xmpl.o

bench class dev mbox xmpl.out

and the input is % vi ch<escape>

csh will complete the prefix “ch” to the only matching file name “chaosnet”, changing the input line to % vi chaosnet

However, given % vi D<escape>

csh will only expand the input to % vi DSC.

and will sound the terminal bell to indicate that the expansion is incomplete,

since there are two file names matching the prefix D.

If a partial file name is followed by the end-of-file character (usually control-D),

then, instead of completing the name, csh will list all file names matching the

prefix. For example, the input % vi D<control-D>

causes all files beginning with D to be listed: DSC.NEW DSC.OLD

while the input line remains unchanged.

The same system of escape and end-of-file can also be used to expand partial

user names, if the word to be completed (or listed) begins with the tilde

character (~). For example, typing cd ~ro<escape>

may produce the expansion cd ~root

The use of the terminal bell to signal errors or multiple matches can be inhibited

by setting the variable nobeep.

Normally, all files in the particular directory are candidates for name completion.

Files with certain suffixes can be excluded from consideration by setting the

variablefignore to the list of suffixes to be ignored. Thus, if fignore is set by the

command % set fignore = (.o .out)

then typing % vi x<escape>

would result in the completion to % vi xmpl.c

ignoring the files "xmpl.o" and "xmpl.out". However, if the only completion

possible requires not ignoring these suffixes, then they are not ignored. In

addition, fignoredoes not affect the listing of file names by control-D. All files

are listed regardless of their suffixes.

History Substitutions

History substitutions place words from previous command input as portions of

new commands, making it easy to repeat commands, repeat arguments of a

previous command in the current command, or fix spelling mistakes in the

previous command with little typing and a high degree of confidence. History

substitutions begin with the character ! and may begin anywhere in the input

stream (provided that they do not nest). This ! may be preceded by a \ to

prevent its special meaning; for convenience, a ! character is passed unchanged

when it is followed by a blank, tab, newline, = or (. (History substitutions also

occur when an input line begins with ^. This special abbreviation is described

below.) Any input line that contains history substitution is echoed on the

terminal before it is executed as it would have been typed without history

substitution.

Commands input from the terminal that consist of one or more words are saved

on the history list. The history substitutions reintroduce sequences of words from

these saved commands into the input stream. The size of the history list is

controlled by thehistory variable; the previous command is always retained,

regardless of the value of the history variable. Commands are numbered

sequentially from 1.

Consider the following output from the history command: 09 write michael

10 ex write.c

11 cat oldwrite.c

12 diff *write.c

The commands are shown with their event numbers. It is not usually necessary

to use event numbers, but the current event number can be made part of the

prompt by placing a ! in the prompt string.

With the current event 13 we can refer to previous events by event number !11,

relatively as in !-2 (referring to the same event), by a prefix of a command word

as in!d for event 12 or !wri for event 9, or by a string contained in a word in the

command as in !?mic? also referring to event 9. These forms, without further

change, simply reintroduce the words of the specified events, each separated by

a single blank. As a special case, !! refers to the previous command;

thus !! alone is a re-do.

To select words from an event we can follow the event specification by a : and a

designator for the desired words. The words of an input line are numbered

from 0, the first (usually command) word being 0, the second word (first

argument) being 1, etc. The basic word designators are:

0 first (command) word

n n'th argument

^ first argument; i.e., ‘1’

$ last argument

% word matched by (immediately preceding) ?s? search

x-y range of words

-y abbreviates ‘0-y’

* abbreviates ‘^-$’, or nothing if only 1 word in event

x* abbreviates ‘x-$’

x- like ‘x*’ but omitting word ‘$’

The : separating the event specification from the word designator can be omitted

if the argument selector begins with a ^, $, *, -, or %. After the optional word

designator, a sequence of modifiers can be placed, each preceded by a :. The

following modifiers are defined:

h Remove a trailing pathname component, leaving the head.

r Remove a trailing ‘.xxx’ component, leaving the root name.

e Remove all but the extension ‘.xxx’ part.

s/l/r/ Substitute l for r.

t Remove all leading pathname components, leaving the tail.

& Repeat the previous substitution.

g Apply the change once on each word, prefixing the above; e.g., ‘g&’.

a Apply the change as many times as possible on a single word, prefixing the above. It can be used together with ‘g’ to apply a substitution globally.

p Print the new command line but do not execute it.

q Quote the substituted words, preventing further substitutions.

x Like ‘q’, but break into words at blanks, tabs, and newlines.

Unless preceded by a g the change is applied only to the first modifiable word.

With substitutions, it is an error for no word to be applicable.

The left-hand side of substitutions are not regular expressions in the sense of the

editors, but instead strings. Any character may be used as the delimiter in place

of /; a \ quotes the delimiter into the l and r strings. The character & in the

right-hand side is replaced by the text from the left. A \ also quotes &. A

NULL l (//) uses the previous string either from an l or from a contextual scan

string s in !?s\?. The trailing delimiter in the substitution may be omitted if a

newline follows immediately as may the trailing ? in a contextual scan.

A history reference may be given without an event specification; e.g., !$. Here,

the reference is to the previous command unless a previous history reference

occurred on the same line in which case this form repeats the previous

reference. Thus “!?foo?^ !$” gives the first and last arguments from the

command matching “?foo?”.

A special abbreviation of a history reference occurs when the first non-blank

character of an input line is a ^. This is equivalent to “!:s^” providing a

convenient shorthand for substitutions on the text of the previous line.

Thus ^lb^lib fixes the spelling of “lib” in the previous command. Finally, a

history substitution may be surrounded with { and }if necessary to insulate it

from the characters that follow. Thus, after ls -ld ~paul we might do !{l}a to

do ls -ld ~paula, while !la would look for a command starting with “la”.

Quotations with ´ and "

The quotation of strings by ' and " can be used to prevent all or some of the

remaining substitutions. Strings enclosed in ' are prevented from any further

interpretation. Strings enclosed in " may be expanded as described below.

In both cases the resulting text becomes (all or part of) a single word; only in

one special case (see Command Substitution, below) does a " quoted string yield

parts of more than one word; ' quoted strings never do.

Alias substitution

The shell maintains a list of aliases that can be established, displayed and

modified by the alias and unalias commands. After a command line is scanned, it

is parsed into distinct commands and the first word of each command, left-to-

right, is checked to see if it has an alias. If it does, then the text that is the alias

for that command is reread with the history mechanism available as though that

command were the previous input line. The resulting words replace the

command and argument list. If no reference is made to the history list, then the

argument list is left unchanged.

Thus if the alias for “ls” is “ls -l”, the command ls /usr would map to ls -l /usr, the argument list here being undisturbed. Similarly, if the alias for “lookup” was

“grep !^ /etc/passwd” then lookup bill would map to grep bill /etc/passwd.

If an alias is found, the word transformation of the input text is performed and

the aliasing process begins again on the reformed input line. Looping is

prevented if the first word of the new text is the same as the old by flagging it to

prevent further aliasing. Other loops are detected and cause an error.

Note that the mechanism allows aliases to introduce parser "metasyntax." Thus,

we can alias print 'pr \!* | lpr' to make a command that pr's its arguments to

the line printer.

Variable Substitution

The shell maintains a set of variables, each of which has as value a list of zero or

more words. Some of these variables are set by the shell or referred to by it. For

instance, the argv variable holds the shell's argument list, and words of this

variable's value are referred to in special ways.

The values of variables may be displayed and changed by using

the set and unsetcommands. Of the variables referred to by the shell a number

are toggles; the shell does not care what their value is, only whether they are

set or not. For instance, theverbose variable is a toggle that causes command

input to be echoed. The setting of this variable results from the -v command-line

option.

Other operations treat variables numerically. The @ command permits numeric

calculations to be performed and the result assigned to a variable. Variable

values are, however, always represented as (zero or more) strings. For the

purposes of numeric operations, the null string is considered to be zero, and the

second and additional words of multiword values are ignored.

After the input line is aliased and parsed, and before each command is executed,

variable substitution is performed, keyed by $ characters. This expansion can be

prevented by preceding the $ with a \ except within double quotes ("), where

substitution always occurs, and within single quotes ('), where it never occurs.

Strings quoted by backticks (` `) are interpreted later (see Command

Substitution, below), so$ substitution does not occur there until later, if at all.

A $ is passed unchanged if followed by a blank, tab, or end-of-line.

Input/output redirections are recognized before variable expansion, and are

variable expanded separately. Otherwise, the command name and entire

argument list are expanded together. It is thus possible for the first (command)

word (to this point) to generate more than one word, the first of which becomes

the command name, and the rest of which become arguments.

Unless enclosed in " or given the :q modifier, the results of variable substitution

may eventually be command and filename substituted. Within ", a variable

whose value consists of multiple words expands to (a portion of) a single word,

with the words of the variable's value separated by blanks. When the :q modifier

is applied to a substitution the variable will expand to multiple words with each

word separated by a blank and quoted to prevent later command or filename

substitution.

The following metasequences are provided for introducing variable values into

the shell input. Except as noted, it is an error to reference a variable that is not

set.

$name ${name}

Are replaced by the words of the value of variable name, each separated by a blank. Braces insulate name from following characters that would otherwise be part of it. Shell variables have names consisting of up to 20 letters and digits starting with a letter. The underscore character is considered a letter. If nameis not a shell variable, but is set in the environment, then that value is returned (but : modifiers and the other forms given below are not available here).

$name[selector] ${name[selector]}

May be used to select only some of the words from the value of name. Theselector is subjected to $ substitution and may consist of a single number or two numbers separated by a -. The first word of a variable's value is numbered1. If the first number of a range is omitted it defaults to 1. If the last number of a range is omitted it defaults to $#name. The selector * selects all words. It is not an error for a range to be empty if the second argument is omitted or in range.

$#name

Gives the number of words in the variable. This is useful for later use in a “$argv[selector]”.

${#name}

$0 Substitutes the name of the file from which command input is being read. An error occurs if the name is not known.

$number ${number}

Equivalent to “$argv[number]”.

$* Equivalent to “$argv[*]”.

The modifiers :e, :h, :t, :r, :q, and :x may be applied to the substitutions above

as may :gh, :gt, and :gr. If braces { } appear in the command form then the

modifiers must appear within the braces. The current implementation allows only

one : modifier on each $ expansion.

The following substitutions may not be modified with : modifiers.

$?name ${?name}

Substitutes the string “1” if name is set, “0” if it is not.

$?0 Substitutes 1 if the current input filename is known, 0 if it is not.

$$ Substitute the (decimal) process number of the (parent) shell. Do NOT use this mechanism for generating temporary file names; see mktemp instead.

$! Substitute the (decimal) process number of the last background process started by this shell.

$< Substitutes a line from the standard input, with no further interpretation. It can be used to read from the keyboard in a shell script.

Command and filename substitution

The remaining substitutions, command and filename substitution, are applied

selectively to the arguments of built-in commands. Here, "selectively" means

that portions of expressions which are not evaluated are not subjected to these

expansions. For commands that are not internal to the shell, the command name

is substituted separately from the argument list. This occurs very late, after

input-output redirection is performed, and in a child of the main shell.

Command Substitution

Command substitution is shown by a command enclosed in `. The output from

such a command is normally broken into separate words at blanks, tabs, and

newlines, with null words being discarded; this text then replaces the original

string. Within double quotes ("), only newlines force new words; blanks and tabs

are preserved.

In any case, the single final newline does not force a new word. Note that it is

therefore possible for a command substitution to yield only part of a word, even

if the command outputs a complete line.

Filename substitution

If a word contains any of the characters *, ?, [, or {, or begins with the

character ~, then that word is a candidate for filename substitution, also known

as “globbing”. This word is then regarded as a pattern, and replaced with an

alphabetically sorted list of file names that match the pattern. In a list of words

specifying filename substitution it is an error for no pattern to match an existing

file name, but it is not required for each pattern to match. Only the

metacharacters *, ?, and [ imply pattern matching, the

characters ~ and { being more akin to abbreviations.

In matching filenames, the character . at the beginning of a filename or

immediately following a /, as well as the character / must be matched explicitly.

The character *matches any string of characters, including the null string. The

character ? matches any single character.

The sequence “[...]” matches any one of the characters enclosed. Within “[...]”,

a pair of characters separated by - matches any character lexically between the

two (inclusive). Within “[...]”, the name of a character class enclosed

in [: and :] stands for the list of all characters belonging to that class. Supported

character classes: • alnum • alpha • blank • cntrl • digit • graph • lower • print • space • upper • punct • xdigit

These match characters using the macros specified in ctype. A character class

may not be used as an endpoint of a range.

The character ~ at the beginning of a filename refers to home directories.

Standing alone, i.e., ~, it expands to the invoker's home directory as reflected in

the value of the variable home. When followed by a name consisting of letters,

digits, and -characters, the shell searches for a user with that name and

substitutes their home directory; thus “~ken” might expand to “/usr/ken” and

“~ken/chmach” to “/usr/ken/chmach”. If the character ~ is followed by a

character other than a letter or /, or does not appear at the beginning of a word,

it is left undisturbed.

The metanotation “a{b,c,d}e” is a shorthand for “abe ace ade”. Left to right

order is preserved, with results of matches being sorted separately at a low level

to preserve this order. This construct can be nested. Thus,

“~source/s1/{oldls,ls}.c” expands to “/usr/source/s1/oldls.c /usr/source/s1/ls.c” without chance of error if the home directory for

“source” is “/usr/source”. Similarly “../{memo,*box}” might expand to

“../memo ../box ../mbox”. (Note that “memo” was not sorted with the results

of the match to “*box”.) As a special case {, }, and {} are passed undisturbed.

Input/output

The standard input and the standard output of a command may be redirected

with the following syntax:

< name Open file name (which is first variable, command, and filename expanded) as the standard input.

<< word Read the shell input up to a line that is identical to word. word is not subjected to variable, command, or filename substitution, and each input line is compared to word before any substitutions are done on the input line. Unless a quoting \, ", ' or ` appears in word, variable and command substitution is performed on the intervening lines, allowing \ to quote $,\ and `. Commands that are substituted have all blanks, tabs, and newlines preserved, except for the final newline which is dropped. The resultant text is placed in an anonymous temporary file that is given to the command as its standard input.

> name >! name >>& name >>&! name

The file name is used as the standard output. If the file does not exist then it is created; if the file exists, it is truncated; its previous contents are lost. If the variable noclobber is set, then the file must not exist or be a character special file (e.g., a terminal or /dev/null) or an error results. This helps prevent accidental destruction of files. Here, the ! forms can be used to suppress this check. The forms involving & route the standard error output into the specified file as well as the standard output. name is expanded in the same way as< input filenames are.

>> name >>& name >>! name >>&! name

Uses file name as the standard output; like > but places output at the end of the file. If the variable noclobber is set, then it is an error for the file not to exist unless one of the ! forms is given. Otherwise similar to >.

A command receives the environment in which the shell was invoked as modified

by the input-output parameters and the presence of the command in a pipeline.

Thus, unlike some previous shells, commands run from a file of shell commands

have no access to the text of the commands by default; instead they receive the

original standard input of the shell. The << mechanism should be used to

present inline data. This permits shell command scripts to function as

components of pipelines and allows the shell to block read its input. Note that

the default standard input for a command run detached is not modified to be the

empty file /dev/null; instead the standard input remains as the original

standard input of the shell. If this is a terminal and if the process attempts to

read from the terminal, then the process will block and the user will be notified

(see Jobs above).

The standard error output may be directed through a pipe with the standard

output. Simply use the form |& instead of just |.

Expressions

Several of the built-in commands (to be described later) take expressions, in

which the operators are similar to those of C, with the same precedence, but

with the opposite grouping: right to left. These expressions appear in

the @, exit, if, and whilecommands. The following operators are available: • || • && • | • ↑ • & • == • != • =~ • !~ • <= • >= • < • > • << • >> • + • -

• * • / • % • ! • ~ • ( • )

Here the precedence increases down the list,

with == != =~ and !~, <= >= < and >,<< and >>, + and -, * / and % being, in groups, at the same level.

The == != =~and !~ operators compare their arguments as strings; all others

operate on numbers. The operators =~ and !~ are like != and == except that

the right hand side is a pattern (containing, e.g., *'s, ?'s, and instances of

“[...]”) against which the left-hand operand is matched. This reduces the need

for use of the switch statement in shell scripts when all that is really needed is

pattern matching.

Strings that begin with 0 are considered octal numbers. Null or missing

arguments are considered 0. The results of all expressions are strings, which

represent decimalnumbers. It is important to note that no two components of an

expression can appear in the same word; except when adjacent to components

of expressions that are syntactically significant to the parser (&, |, <, >, (,

and )), they should be surrounded by spaces.

Also available in expressions as primitive operands are command executions

enclosed in { and } and file enquiries of the form -l name where l is one of:

r read access

w write access

x execute access

e existence

o ownership

z zero size

f plain file

d directory

The specified name is command and filename expanded and then tested to see if

it has the specified relationship to the real user. If the file does not exist or is

inaccessible then all enquiries return false, i.e., 0. Command executions

succeed, returning true, i.e., 1, if the command exits with status 0, otherwise

they fail, returning false, i.e., 0. If more detailed status information is required

then the command should be executed outside an expression and the variable

status examined.

Control Flow

The shell contains several commands that can be used to regulate the flow of

control in command files (shell scripts) and (in limited but useful ways) from

terminal input. These commands all operate by forcing the shell to reread or skip

in its input and, because of the implementation, restrict the placement of some

of the commands.

The foreach, switch, and while statements, as well as the if-then-else form

of the ifstatement require that the major keywords appear in a single simple

command on an input line as shown below.

If the shell's input is not seekable, the shell buffers up input whenever a loop is

being read and performs seeks in this internal buffer to accomplish the rereading

implied by the loop. (To the extent that this allows, backward goto's will succeed

on non-seekable inputs.)

Built-In Commands

Built-in commands are executed within the shell. If a built-in command occurs as

any component of a pipeline except the last then it is executed in a sub-shell.

alias alias name alias name wordlist

The first form prints all aliases. The second form prints the alias for name. The final form assigns the specified wordlist as the alias of name; wordlist is command and filename substituted. name is not allowed to be “alias” or “unalias”.

alloc Shows the amount of dynamic memory acquired, broken down into used and free memory. With an argument shows the number of free and used blocks in each size category. The categories start at size 8 and double at each step. This command's output may vary across system types, since systems other than the VAX may use a different memory allocator.

bg bg %job ...

Puts the current or specified jobs into the background, continuing them if they were stopped.

break Causes execution to resume after the end of the nearest enclosing foreach orwhile. The remaining commands on the current line are executed. Multi-level breaks are thus possible by writing them all on one line.

breaksw Causes a break from a switch, resuming after the endsw.

case label: A label in a switch statement as discussed below.

cd cd name chdir chdir name

Change the shell's working directory to directory name. If no argument is given then change to the home directory of the user. If name is not found as a subdirectory of the current directory (and does not begin with /, ./ or ../), then each component of the variable cdpath is checked to see if it has a subdirectory name. Finally, if all else fails but name is a shell variable whose value begins with /, then this is tried to see if it is a directory.

continue Continue execution of the nearest enclosing while or foreach. The rest of the commands on the current line are executed.

default: Labels the default case in a switch statement. The default should come after all case labels.

dirs Prints the directory stack; the top of the stack is at the left, the first directory in the stack being the current directory.

echo wordlist echo -n wordlist

The specified words are written to the shell's standard output, separated by spaces, and terminated with a newline unless the -n option is specified.

else end endif endsw

See the description of the foreach, if, switch, and while statements below.

eval arg ... Mimics eval in sh: the arguments are read as input to the shell and the resulting command(s) executed in the context of the current shell. This is usually used to execute commands generated as the result of command or variable substitution, since parsing occurs before these substitutions. Seetset's manual for an example of using eval.

exec command The specified command is executed in place of the current shell.

exit exit (expr)

The shell exits either with the value of the status variable (first form) or with the value of the specified expr (second form).

fg

Brings the current or specified jobs into the foreground, continuing them if they were stopped.

fg %job ...

foreach name (wordlist) ... end

The variable name is successively set to each member of wordlist and the sequence of commands between this command and the matching end are executed. (Both foreach and end must appear alone on separate lines.) The built-in command continue may be used to continue the loop prematurely and the built-in command break to terminate it prematurely. When this command is read from the terminal, the loop is read once prompting with ? before any statements in the loop are executed. If you make a mistake typing in a loop at the terminal you can rub it out.

glob wordlist Like echo but no \ escapes are recognized and words are delimited by NULcharacters in the output. Useful for programs that wish to use the shell to filename expand a list of words.

goto word The specified word is filename and command expanded to yield a string of the form label. The shell rewinds its input as much as possible and searches for a line of the form “label:”, possibly preceded by blanks or tabs. Execution continues after the specified line.

hashstat Print a statistics line showing how effective the internal hash table has been at locating commands (and avoiding exec´s). An exec is attempted for each component of the path where the hash function indicates a possible hit, and in each component that does not begin with a /.

history history n history -h n history -r n

Displays the history event list; if n is given, only the n most recent events are printed. The -h option causes the history list to be printed without leading numbers. This format produces files suitable for sourcing using the -h option to source. The -r option reverses the order of printout to be most recent first instead of oldest first.

if (expr) command If the specified expression evaluates to true, then the single command with arguments is executed. Variable substitution on command happens early, at the same time it does for the rest of the if command. command must be a simple command, not a pipeline, a command list, or a parenthesized command list. Input/output redirection occurs even if expr is false, i.e., when command is not executed (this is actually a bug).

if (expr) then ... else if (expr2)then ...

If the specified expr is true then the commands up to the first else are executed; otherwise if expr2 is true then the commands up to the second elseare executed, etc. Any number of else-if pairs are possible; only one endif is

else ... endif

needed. The else part is likewise optional. (The words else and endif must appear at the beginning of input lines; the if must appear alone on its input line or after an else.)

jobs jobs -l

Lists the active jobs; the -l option lists process IDs in addition to the normal information.

kill %job kill [-s signal_name] pid kill -sig pid ... kill -l [exit_status]

Sends either the SIGTERM (terminate) signal or the specified signal to the specified jobs or processes. Signals are either given by number or by names (as given in ⟨signal.h⟩, stripped of the prefix “SIG”). The signal names are listed by “kill -l”; if an exit_status is specified, only the corresponding signal name will be written. There is no default; just saying “kill” does not send a signal to the current job. If the signal being sent is SIGTERM (terminate) orSIGHUP (hangup), then the job or process will be sent a SIGCONT (continue) signal as well.

limit limit resource limit resource maximum-use limit -h limit -h resource limit -h resource maximum-use

Limits the consumption by the current process and each process it creates to not individually exceed maximum-use on the specified resource. If nomaximum-use is given, then the current limit is printed; if no resource is given, then all limitations are given. If the -h flag is given, the hard limits are used instead of the current limits. The hard limits impose a ceiling on the values of the current limits. Only the superuser may raise the hard limits, but a user may lower or raise the current limits within the legal range. Resources controllable currently include: cputime: the maximum number of CPU-seconds to be used by each process. filesize: the largest single file (in bytes) that can be created. datasize: the maximum growth of the data+stack region via sbrk beyond the end of the program text. stacksize: the maximum size of the automatically-extended stack region. coredumpsize: the size of the largest core dump (in bytes) that will be created. memoryuse: the maximum size (in bytes) to which a process's resident set size (RSS) may grow. memorylocked: The maximum size (in bytes) which a process may lock into memory using the mlock function.

maxproc: The maximum number of simultaneous processes for this user ID. openfiles: The maximum number of simultaneous open files for this user ID. vmemoryuse: the maximum size (in bytes) to which a process's total size may grow. The maximum-use may be given as a (floating point or integer) number followed by a scale factor. For all limits other than cputime the default scale isk or “kilobytes” (1024 bytes); a scale factor of m or “megabytes” may also be used. For cputime the default scale is “seconds”; a scale factor of m for minutes or h for hours, or a time of the form “mm:ss” giving minutes and seconds also may be used. For both resource names and scale factors, unambiguous prefixes of the names suffice.

login Terminate a login shell, replacing it with an instance of /usr/bin/login. This is one way to log off, included for compatibility with sh.

logout Terminate a login shell. Especially useful if ignoreeof is set.

nice nice +number nice command nice +number command

The first form sets the scheduling priority for this shell to 4. The second form sets the priority to the given number. The final two forms run command at priority 4 and number respectively. The greater the number, the less CPU the process will get. The superuser may specify negative priority by using “nice -number ...”. command is always executed in a sub-shell, and the restrictions placed on commands in simple if statements apply.

nohup nohup command

The first form can be used in shell scripts to cause hangups to be ignored for the remainder of the script. The second form causes the specified command to be run with hangups ignored. All processes detached with & are effectivelynohup´ed.

notify notify %job ...

Causes the shell to notify the user asynchronously when the status of the current or specified jobs change; normally notification is presented before a prompt. This is automatic if the shell variable notify is set.

onintr onintr -

Control the action of the shell on interrupts. The first form restores the default action of the shell on interrupts, which is to terminate shell scripts or to return to the terminal command input level. The second form onintr - causes all

onintr label interrupts to be ignored. The final form causes the shell to execute a gotolabel when an interrupt is received or a child process terminates because it was interrupted. In any case, if the shell is running detached and interrupts are being ignored, all forms of onintr have no meaning and interrupts continue to be ignored by the shell and all invoked commands. Finally, onintr statements are ignored in the system startup files where interrupts are disabled (/etc/csh.cshrc,/etc/csh.login).

popd popd +n

Pops the directory stack, returning to the new top directory. With an argument “+n” discards the n´th entry in the stack. The members of the directory stack are numbered from the top starting at 0.

pushd pushd name pushd +n

With no arguments, pushd exchanges the top two elements of the directorystack. Given a name argument, pushd changes to the new directory (ala cd) and pushes the old current working directory (as in pwd) onto the directory stack. With a numeric argument, pushd rotates the n´th argument of the directory stack around to be the top element and changes to it. The members of the directory stack are numbered from the top starting at 0.

rehash Causes the internal hash table of the contents of the directories in the pathvariable to be recomputed. This is needed if new commands are added to directories in the path while you are logged in. This should only be necessary if you add commands to one of your own directories, or if a systems programmer changes the contents of a system directory.

repeat count command

The specified command, which is subject to the same restrictions as the command in the one line if statement above, is executed count times. I/Oredirections occur exactly once, even if count is 0.

set set name set name=word setname[index]=word set name=(wordlist)

The first form of the command shows the value of all shell variables. Variables that have other than a single word as their value print as a parenthesized word list. The second form sets name to the null string. The third form sets name to the single word. The fourth form sets the index'th component of name to word; this component must already exist. The final form sets name to the list of words in wordlist. The value is always command and filename expanded. These arguments may be repeated to set multiple values in a single setcommand. Note however, that variable expansion happens for all arguments before any setting occurs.

setenv setenv name setenv name value

The first form lists all current environment variables. It is equivalent toprintenv. The last form sets the value of environment variable name to be value, a single string. The second form sets name to an empty string. The most commonly used environment variables USER, TERM, and PATH are automatically imported to and exported from the csh variables user, term, andpath; there is no need to use setenv for these.

shift shift variable

The members of argv are shifted to the left, discarding argv[1]. It is an error for argv not to be set or to have less than one word as value. The second form performs the same function on the specified variable.

source name source -h name

The shell reads commands from name. source commands may be nested; if they are nested too deeply the shell may run out of file descriptors. An error in a source at any level terminates all nested source commands. Normally input during source commands is not placed on the history list; the -h option causes the commands to be placed on the history list without being executed.

stop stop %job ...

Stops the current or specified jobs that are executing in the background.

suspend Causes the shell to stop in its tracks, much as if it had been sent a stop signal with ^Z. This is most often used to stop shells started by su.

switch (string) case str1: ... breaksw ... default: ... breaksw endsw

Each case label is successively matched against the specified string, which is first command and filename expanded. The file metacharacters *, ? and “[...]” may be used in the case labels, which are variable expanded. If none of the labels match before the “default” label is found, then the execution begins after the default label. Each case label and the default label must appear at the beginning of a line. The command breaksw causes execution to continue after the endsw. Otherwise control may fall through case labels and the default label as in C. If no label matches and there is no default, execution continues after the endsw.

time time command

With no argument, a summary of time used by this shell and its children is printed. If arguments are given the specified simple command is timed and a time summary as described under the time variable is printed. If necessary, an extra shell is created to print the time statistic when the command completes.

umask

The file creation mask is displayed (first form) or set to the specified value(second form). The mask is given in octal.

umask value Common values for the mask are002 giving all access to the group and read and execute access to others or022 giving all access except write access for users in the group or others.

unalias pattern All aliases whose names match the specified pattern are discarded. Thus all aliases are removed by unalias *. It is not an error for nothing to be unaliased.

unhash Use of the internal hash table to speed location of executed programs is disabled.

unlimit unlimit resource unlimit -h unlimit -hresource

Removes the limitation on resource. If no resource is specified, then all resource limitations are removed. If -h is given, the corresponding hard limits are removed. Only the superuser may do this.

unset pattern All variables whose names match the specified pattern are removed. Thus all variables are removed by unset *; this has noticeably distasteful side-effects. It is not an error for nothing to be unset.

unsetenv pattern Removes all variables whose names match the specified pattern from the environment. See also the setenv command above and printenv.

wait Wait for all background jobs. If the shell is interactive, then an interrupt can disrupt the wait. After the interrupt, the shell prints names and job numbers of all jobs known to be outstanding.

which command Displays the resolved command that will be executed by the shell.

while (expr) ... end

While the specified expression evaluates to non-zero, the commands between the while and the matching end are evaluated. break and continue may be used to terminate or continue the loop prematurely. (The while and end must appear alone on their input lines.) Prompting occurs here the first time through the loop as for the foreach statement if the input is a terminal.

%job Brings the specified job into the foreground.

%job & Continues the specified job in the background.

@ @ name=

The first form prints the values of all the shell variables. The second form sets the specified name to the value of expr. If the expression contains <, >, & or |then at least this part of

expr @name[index]= expr

the expression must be placed within ( ). The third form assigns the value of expr to the index'th argument of name. Both name and its index'th component must already exist. The operators *=, +=, etc. are available as in C. The space separating the name from the assignment operator is optional. Spaces are, however, mandatory in separating components of expr, which would otherwise be single words. Special postfix ++ and -- operators increment and decrement name respectively; i.e., “@ i++”.

Pre-defined and environment variables

The following variables have special meaning to the shell. Of

these, argv, cwd,home, path, prompt, shell and status are always set by the

shell. Except for cwdand status, this setting occurs only at initialization; these

variables will not then be modified unless done explicitly by the user.

The shell copies the environment variable USER into the

variable user, TERM intoterm, and HOME into home, and copies these back

into the environment whenever the normal shell variables are reset. The

environment variable PATH is likewise handled; it is not necessary to worry

about its setting other than in the file .cshrc as inferior csh processes will import

the definition of path from the environment, and re-export it if you then change

it.

argv Set to the arguments to the shell, it is from this variable that positional parameters are substituted; i.e., “$1” is replaced by “$argv[1]”, etc.

cdpath Gives a list of alternate directories searched to find subdirectories in chdir commands.

cwd The full pathname of the current directory.

echo Set when the -x command-line option is given. Causes each command and its arguments to be echoed just before it is executed. For non-built-in commands all expansions occur before echoing. Built-in commands are echoed before command and filename substitution, since these substitutions are then done selectively.

filec Enable file name completion.

histchars Can be given a string value to change the characters used in history substitution. The first character of its value is used as the history substitution character, replacing the default character !. The second character of its value replaces the character ^ in quick substitutions.

histfile Can be set to the pathname where history is going to be saved/restored.

history Can be given a numeric value to control the size of the history list. Any command that has been referenced in this many events will not be discarded. Too large values of history may run the shell out of memory. The last executed command is always saved on the history list.

home The home directory of the invoker, initialized from the environment. The filename expansion of “~” refers to this variable.

ignoreeof If set the shell ignores end-of-file from input devices which are terminals. This prevents shells from accidentally being killed by control-Ds.

mail The files where the shell checks for mail. This checking is done after each command completion that will result in a prompt, if a specified interval has elapsed. The shell says “You have new mail.” if the file exists with an access time not greater than its modify time. If the first word of the value of mail is numeric it specifies a different mail checking interval, in seconds, than the default, which is 10 minutes. If multiple mail files are specified, then the shell says “New mail in name” when there is mail in the file name.

noclobber As described in the section on Input/output, restrictions are placed on output redirection to ensure that files are not accidentally destroyed, and that >>redirections refer to existing files.

noglob If set, filename expansion is inhibited. This inhibition is most useful in shell scripts that are not dealing with filenames, or after a list of filenames has been obtained and further expansions are not desirable.

nonomatch If set, it is not an error for a filename expansion to not match any existing files; instead the primitive pattern is returned. It is still an error for the primitive pattern to be malformed; i.e., “echo [” still gives an error.

notify If set, the shell notifies asynchronously of job completions; the default is to present job completions just before printing a prompt.

path Each word of the path variable specifies a directory in which commands are to be sought for execution. A null word specifies the current directory. If there is no path variable then only full path names will execute. The usual search path is “.”, “/bin”, “/usr/bin”, “/sbin” and “/usr/sbin”, but this may vary from system to system. For the superuser the default search path is “/bin”, “/usr/bin”, “/sbin”, and “/usr/sbin”. A shell that is given neither the -c nor the -t option will normally hash the contents of the directories in the path variable after

reading .cshrc, and each time the path variable is reset. If new commands are added to these directories while the shell is active, it may be necessary to do a rehash or the commands may not be found.

prompt The string that is printed before each command is read from an interactive terminal input. If a ! appears in the string it will be replaced by the current event number unless a preceding \ is given. Default is “%”, or “#” for the superuser.

savehist Is given a numeric value to control the number of entries of the history list that are saved in ~/.history when the user logs out. Any command that has been referenced in this many events will be saved. During start up the shell sources ~/.history into the history list enabling history to be saved across logins. Too large values ofsavehist will slow down the shell during start up. If savehist is just set, the shell will use the value of history.

shell The file in which the shell resides. This variable is used in forking shells to interpret files that have execute bits set, but which are not executable by the system. (See the description of Non-built-in command execution below.) Initialized to the (system-dependent) home of the shell.

status The status returned by the last command. If it terminated abnormally, then 0200 is added to the status. Built-in commands that fail return exit status 1, all other built-in commands set status to 0.

time Controls automatic timing of commands. If set, then any command that takes more than this many CPU seconds will cause a line giving user, system, and real times, and a utilization percentage which is the ratio of user plus system times to real time to be printed when it terminates.

verbose Set by the -v command-line option, causes the words of each command to be printed after history substitution.

Non-built-in command execution

When a command to be executed is found to not be a built-in command the shell

attempts to execute the command via execve. Each word in the variable path

names a directory from which the shell will attempt to execute the command. If

it is given neither a -c nor a -t option, the shell will hash the names in these

directories into an internal table so that it will only try an exec in a directory if

there is a possibility that the command resides there. This shortcut greatly

speeds command location when many directories are present in the search path.

If this mechanism has been turned off (via unhash), or if the shell was given a -c or -t argument, and in any case for each directory component of path that

does not begin with a /, the shell concatenates with the given command name

to form a path name of a file which it then attempts to execute.

Parenthesized commands are always executed in a sub-shell. Thus (cd; pwd); pwd

prints the home directory; leaving you where you were (printing this after the

home directory), while cd; pwd

leaves you in the home directory. Parenthesized commands are most often used

to prevent chdir from affecting the current shell.

If the file has execute permissions but is not an executable binary to the system,

then it is assumed to be a file containing shell commands and a new shell is

spawned to read it.

If there is an alias for shell then the words of the alias will be prepended to the

argument list to form the shell command. The first word of the alias should be

the full path name of the shell (e.g., “$shell”). Note that this is a special, late

occurring, case of alias substitution, and only allows words to be prepended to

the argument list without change.

Signal Handling

The shell normally ignores SIGQUIT signals. Jobs running detached (either

by & or thebg or %... & commands) are immune to signals generated from the

keyboard, including hangups. Other signals have the values which the shell

inherited from its parent. The shell's handling of interrupts and terminate signals

in shell scripts can be controlled by onintr. Login shells catch

the SIGTERM (terminate) signal; otherwise this signal is passed on to children

from the state in the shell's parent. Interrupts are not allowed when a login shell

is reading the file .logout.

Limitations

Word lengths: Words can be no longer than 1024 characters. The number of

arguments to a command that involves filename expansion is limited to 1/6th

the number of characters allowed in an argument list. Command substitutions

may substitute no more characters than are allowed in an argument list. To

detect looping, the shell restricts the number of alias substitutions on a single

line to 20.

Files

~/.cshrc read at beginning of execution by each shell

~/.login read by login shell, after .cshrc at login

~/.logout read by login shell, at logout

/bin/sh standard shell, for shell scripts not starting with a #

/tmp/sh.* temporary file for <<

/etc/passwd source of home directories for “~name”

Examples

csh

Executes and runs the C Shell (if present).

See the .cshrc definition page for an example of the .cshrc file and additional

information about this file.

Related commands

bash bc echo login ls more ps sh

Linux and Unix ksh command Quick links

About ksh Syntax Examples Related commands Linux and Unix main page

About ksh

ksh is the Korn Shell, a command shell and programming language. Syntax

ksh [ ±abcefhikmnoprstuvxBCDP ] [ -R file ] [ ±o option ] ... [ - ] [ arg ... ]

rksh [ ±abcefhikmnoprstuvxBCD ] [ -R file ] [ ±o option ] ... [ - ] [ arg ... ]

Description

ksh is a command and programming language that executes commands read

from aterminal 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. See Invocation below for the meaning ofarguments to the

shell.

Definitions

In ksh, a metacharacter is one of the following characters: • ; • & • ( • ) • < • > • newline • space • tab

A blank is a tab or a space. An identifier is a sequence of letters, digits, or

underscores starting with a letter or underscore. Identifiers are used as

components of variablenames. A vname is a sequence of one or more identifiers

separated by a dot (".") and optionally preceded by a set of two dots

(".."). Vnames are used as function and variable names. A word is a sequence of

characters from the character set defined by the current locale, excluding non-

quoted metacharacters.

A command is a sequence of characters in the syntax of the shell language. The

shell reads each command and carries out the desired action either directly or by

invoking separate utilities. A built-in command is a command that is carried out

by the shell itself without creating a separate process. Some commands are

built-in purely for convenience and are not documented here. Built-ins that cause

side effects in the shell environment and built-ins that are found before

performing a path search (seeExecution below) are documented here. For

historical reasons, some of these built-ins behave differently than other built-ins

and are called special built-ins.

Commands

A simple-command is a list of variable assignments (see Variable

Assignments below) or a sequence of blank-separated words which may be

preceded by a list of variable assignments (see Environment below). The first

word specifies the name of the command to be executed. Except as specified

below, the remaining words are passed as arguments to the invoked command.

The command name is passed as argument 0 (see exec). The value of a simple-

command is its exit status; 0-255 if it terminates normally; 256+signum if it

terminates abnormally (the name of the signal corresponding to the exit status

can be obtained via the -l option of the kill built-in utility).

A pipeline is a sequence of one or more commands separated by a vertical bar

("|"). The standard output of each command but the last is connected by a pipe

to thestandard 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 exit status of the last command

unless the pipefail option is enabled. Each pipeline can be preceded by the

reserved character "!" which causes the exit status of the pipeline to become 0 if

the exit status of the last command is non-zero, and 1 if the exit status of the

last command is 0.

A list is a sequence of one or more pipelines separated 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 does not

wait for that pipeline to finish). The symbol |& causes asynchronous execution of

the preceding pipeline with a two-way pipe established to the parent shell; the

standard input and output of the spawned pipeline can be written to and read

from by the parent shell by applying the redirection operators <& and >&with

arg p to commands and by using -p option of the built-in

commands read andprint described later. The symbol && (||) causes the list

following it to be executed only if the preceding pipeline returns a zero (non-

zero) value. One or more new-lines may appear in a list instead of a semicolon,

to delimit a command. The first item of the first pipeline of a list that is a simple

command not beginning with a redirection, and not occurring within

a while, until, or if list, can be preceded by a semicolon. This semicolon is

ignored unless the showme option is enabled as described with the setbuilt-in

below.

A command is either a simple-command or one of the following. Unless

otherwise stated, the value returned by a command is that of the last simple-

command executed in the command.

for vname [ inword ... ] ;dolist ;done

Each time a for command is executed, vname is set to the next word taken from the in word list. If "in word ..." is omitted, then the for command executes the dolist once for each positional parameter that is set

starting from 1 (see Parameter Expansion below). Execution ends when there are no more words in the list.

for (( [expr1]; [expr2] ;[expr3] )) ;dolist ;done

The arithmetic expression expr1 is evaluated first (see Arithmetic Evaluationbelow). The arithmetic expression expr2 is repeatedly evaluated until it evaluates to zero and when non-zero, list is executed and the arithmetic expression expr3evaluated. If any expression is omitted, then it behaves as if it evaluated to 1.

select vname[ in word ... ] ;do list ;done

A select command prints on standard error (file descriptor 2) the set of words, each preceded by a number. If "in word ..." is omitted, then the positional parameters starting from 1 are used instead (see Parameter Expansion below). ThePS3 prompt is printed and a line is read from the standard input. If this line consists of the number of one of the listed words, then the value of the variablevname is set to the word corresponding to this number. If this line is empty, the selection list is printed again. Otherwise the value of the variable vname is set tonull. The contents of the line read from standard input is saved in the variable REPLY. The list is executed for each selection until a break or end-of-file is encountered. If the REPLY variable is set to null by the execution of list, then the selection list is printed before displaying the PS3 prompt for the next selection.

case word in [ [(]pattern [ ⎪pattern ] ... )list ;; ] ...esac

A case command executes the list associated with the first pattern that matchesword. The form of the patterns is the same as that used for file-name generation (see File Name Generation below). The ;; operator causes execution of case toterminate. If ;& is used in place of ;; the next subsequent list, if any, is executed.

if list ;thenlist [ ;elif list;then list ] ... [ ;else list ] ;fi

The list following if is executed and, if it returns a zero exit status, the listfollowing the first then is executed. Otherwise, the list following elif is executed and, if its value is zero, the list following the next then is executed. Failing each successive elif list, the else list is executed. If the if list has non-zero exit status and there is no else list, then

the if command returns a zero exit status.

while list ;dolist ;done until list ;dolist ;done

A while command repeatedly executes the while list and, if the exit status of the last command in the list is zero, executes the do list; otherwise the loop terminates. If no commands in the do list are executed, then the while command returns a zero exit status; until may be used in place of while to negate the loop termination test.

((expression)) The expression is evaluated using the rules for arithmetic evaluation described below. If the value of the arithmetic expression is non-zero, the exit status is 0, otherwise the exit status is 1.

(list) Execute list in a separate environment. Note, that if two adjacent open parentheses are needed for nesting, a space must be inserted to avoid evaluation as an arithmetic command as described above.

{ list;} list is simply executed. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur at the beginning of a line or after a ; in order to be recognized.

[[ expression]] Evaluates expression and returns a zero exit status when expression is true. SeeConditional Expressions below for a description of expression.

functionvarname { list;} varname () {list ;}

Define a function which is referenced by varname. A function whose varnamecontains a . is called a discipline function and the portion of the varname preceding the last . must refer to an existing variable. The body of the function is the list of commands between { and }. A function defined with the "function varname" syntax can also be used as an argument to the . special built-in command to get the equivalent behavior as if the varname() syntax was used to define it. (SeeFunctions below.)

namespaceidentifier { list;} Defines or uses the name space identifier and runs the commands in list in this name space. (See Name Spaces below.)

& [ name [arg... ] ] Causes subsequent list commands terminated by & to be placed in the background job pool

name. If name is omitted a default unnamed pool is used. Commands in a named background pool may be executed remotely.

time [ pipeline] If pipeline is omitted the user and system time for the current shell and completedchild processes is printed on standard error. Otherwise, pipeline is executed and the elapsed time as well as the user and system time are printed on standard error. The TIMEFORMAT variable may be set to a format string that specifies how the timing information should be displayed. See Shell Variables below for a description of the TIMEFORMAT variable.

The following reserved words are recognized as reserved only when they are the

first word of a command and 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 command or can be arguments to the typeset, enum, export, or read‐only special built-in

commands as well as to other declaration commands created as types. The

syntax for an assignment is of the form:

varname=word varname[word]=word

No space is permitted between varname and the = or between = and word.

varname=(assign_list No space is permitted between varname and the =. The

) variable varname is unset before the assignment. An assign_list can be one of the following:

word ... Indexed array assignment.

[word]=word... Associative array assignment. If preceded by typeset -athis will create an indexed array instead.

assignment... Compound variable assignment. This creates a compound variable varname with sub-variables of the formvarname.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 varname will also be displayed as part of the value of varname. If no assignments are specified,varname will be a compound variable allowing subsequence child elements to be defined.

typeset[options]assignment...

Nested variable assignment. Multiple assignments can be specified by separating each of them with a ;. The previous value is unset before the assignment. Other declaration commands such as readonly, enum, and other declaration commands can be used in place of typeset.

. filename Include the assignment commands contained in filename.

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, word is

evaluated as an arithmetic expression and added to the current value. When

applied to a stringvariable, the value defined by word is appended to the value.

For compound assignments, the previous value is not unset and the new values

are appended to the current ones provided that the types are compatible.

The right hand side of a variable assignment undergoes all the expansion listed

below except word splitting, brace expansion, and file name generation. When

the left hand side is an assignment is a compound variable and the right hand is

the name of a compound variable, the compound variable on the right will be

copied or appended to the compound variable on the left.

Comments

A word beginning with # is considered the beginning of a comment, causing that

word and all the following characters up to a newline to be ignored.

Aliasing

The first word of each command is replaced by the text of an alias if an alias for

this word has been defined. An alias name consists of any number of characters

excluding metacharacters, quoting characters, file expansion characters,

parameter expansion and command substitution characters, the

characters / and =. The replacement string can contain any valid shell script

including the metacharacters listed above. The first word of each command in

the replaced text, other than any that are in the process of being replaced, will

be tested for aliases. If the last character of the alias value is a blank then the

word following the alias will also be checked for alias substitution. Aliases can be

used to redefine built-in commands but cannot be used to redefine the reserved

words listed above. Aliases can be created and listed with the alias command

and can be removed with the unalias command. Aliasing is performed when

scripts are read, not while they are executed. Therefore, for an alias to take

effect, the aliasdefinition command has to be executed before the command

which references the alias is read.

The following aliases are compiled into the shell but can be unset or redefined: • autoload=′typeset -fu′ • command=′command ′ • compound=′typeset -C′ • fc=hist • 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 word is checked to see if it begins with an unquoted "∼". For tilde substitution, word also refers to the word portion of

parameter expansion (see Parameter Expansion below). If it does, then the word

up to a / is checked to see if it matches a user name in the password database. If a match is found, the ∼ and the matched login name are replaced by the login

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 a variable assignment, tilde substitution is attempted when the value of the assignment begins with a ∼, and when

a ∼ appears after a :. The : also terminates a ∼ login name.

Command Substitution

The standard output from a command list enclosed in parentheses 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 all of a word; trailing

newlines are removed. In the second case, the { and } are treated as a reserved

words so that {must be followed by a blank and } must appear at the beginning

of the line or follow a;. In the third (obsolete) form, the string between the

quotes is processed for special quoting characters before the command is

executed (see Quoting 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 descriptor n.

Except for the second form, the command list is run in a subshell so that no side

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 double parentheses preceded by a dollar

sign ("$(())") is replaced by the value of the arithmetic expression within the

double parentheses.

Process Substitution

Each command argument of the form <(list) or >(list) will run

process listasynchronously connected to some file in /dev/fd if this directory

exists, or else a fifoa temporary directory. 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 from the files file1 and file2 respectively, pastes the results

together, and sends it to the processes process1 and process2, as well as

putting it onto the standard output. Note that the file, which is passed as an

argument to the command, is a UNIX pipe so programs that expect to lseek on

the file will not work.

Process substitution of the form <(list) can also be used with the < redirection

operator which causes the output of list to be standard input or the input for

whatever file descriptor is specified.

Parameter Expansion

A parameter is a variable, one or more digits, or any of the characters ∗, @, #, ?, -, $, and !. A variable is denoted by a vname. To create a

variable whose vname contains a., a variable whose vname consists of

everything before the last . must already exist. A variable has a value and zero

or more attributes. Variables can be assigned values and attributes by using

the typeset special built-in command. The attributes supported by the shell are

described later with the typeset special built-in command. Exported variables

pass values and attributes to the environment.

The shell supports both indexed and associative arrays. An element of an array

variable is referenced by a subscript. A subscript for an indexed array is denoted

by an arithmetic expression (see Arithmetic evaluation below) between a [ and

a ]. To assign values to an indexed array, use "vname=(value ...)" or "set -A vname value ..." . The value of all non-negative subscripts must be in the

range of 0 through 4,194,303. A negative subscript is treated as an offset from

the maximum current index +1 so that -1 refers to the last element. Indexed

arrays can be declared with the -a option to typeset. Indexed arrays need not

be declared. Any reference to a variable with a valid subscript is legal and an

array will be created if necessary.

An associative array is created with the -A option to typeset. A subscript for an

associative array is denoted by a string enclosed between [ and ].

Referencing any array without a subscript is equivalent to referencing the array

with subscript 0.

The value of a variable may be assigned by writing: vname=value [ vname=value ] ...

or

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

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

Attributes assigned by the typeset special built-in command apply to all

elements of the array. An array element can be a simple variable, a compound

variable or an array variable. An element of an indexed array can be either an

indexed array or an associative array. An element of an associative array can

also be either. To refer to an array element that is part of an array element,

concatenate the subscript in brackets. For example, to refer to

the foobar element of an associative array that is defined as the third element

of the indexed array, use ${vname[3][foobar]}.

A nameref is a variable that is a reference to another variable. A nameref is created with the -n attribute of typeset. The value of the variable at the time of

the typesetcommand becomes the variable that will be referenced whenever

the nameref variable is used. The name of a nameref cannot contain a ".". When a variable or function name contains a ".", and the portion of the name up

to the first "." matches the name of a nameref, the variable referred to is

obtained by replacing the nameref portion with the name of the variable

referenced 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. Anameref provides a

convenient way to refer to the variable inside a function whose name is passed

as an argument to a function. For example, if the name of a variable is passed as

the first argument to a function, the command typeset -n var=$1

inside the function causes references and assignments to var to be references

and assignments to the variable whose name has been passed to the function.

If any of the floating point attributes, -E, -F, or -X, or the integer attribute, -i, is set for vname, then the value is subject to arithmetic evaluation as described

below.

Positional parameters (parameters denoted by a number) may be assigned

values with the set special built-in command.

Parameter $0 is set from argument zero when the shell is invoked.

The character $ is used to introduce substitutable parameters.

${parameter} The shell reads all the characters from ${ to the matching } as part of the same word even if it contains braces or metacharacters. The value, if any, of the parameter is substituted. The braces are required when parameter is followed by a letter, digit, or underscore that 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 subscripted unless it is part of an Arithmetic Expression or a Conditional Expression. Ifparameter is one or more digits then it is a positional parameter. A positional parameter of more than one digit must be enclosed in braces. If parameter is ∗ or @, then all the positional parameters, starting with $1, are substituted (separated by a field separator character). If an array vname with last subscript ∗ @, or for index arrays of the form sub1 .. sub2. is used, then the

value for each of the elements between sub1 and sub2 inclusive (or all elements for ∗ and @) is substituted, separated by the first character of the value of IFS.

${#parameter} If parameter is ∗ or @, the number of positional parameters is substituted. Otherwise, the length of the value of the parameter is substituted.

${#vname[*]} ${#vname[@]}

The number of elements in the array vname is substituted.

${@vname} Expands to the type name (See Type Variables below) or attributes of the variable referred to by vname.

${!vname} Expands to the name of the variable referred to by vname. This will be vname except when vname is a name reference.

${!vname[subscript]} Expands to name of the subscript unless subscript is *, @ or of the form sub1 .. sub2. When subscript is *, the list of array subscripts for vname is generated. For a variable that is not an array, the value is 0 if the variable is set. Otherwise it is null. When subscript is @, same as above; except that when used in double quotes, each array subscript yields a separate argument. When subscript is of the form sub1 .. sub2 it expands to the list of subscripts between sub1 and sub2, inclusive, using the same quoting rules as @.

${!prefix*} Expands to the names of the variables whose names begin withprefix.

${parameter:-word} If parameter is set and is non-null then substitute its value; otherwise substitute word.

${parameter:=word} If parameter is not set or is null then set it to word; the value of the parameter is then substituted. Positional parameters may not be assigned to in this way.

${parameter:?word} If parameter is set and is non-null then substitute its value; otherwise, print word and exit from the shell (if not interactive). If word is omitted then a standard message is printed.

${parameter:+word} If parameter is set and is non-null then

substitute word; otherwise substitute nothing. In the above, word is not evaluated unless it is to be used as the substituted string, so that, in the following example, pwd is executed only if d is not set or is null: print ${d:-$(pwd)}

If the colon (":") is omitted from the above expressions, then the shell only checks whether parameter is set or not.

${parameter:offset:length} ${parameter:offset}

Expands to the portion of the value of parameter starting at the character (counting from 0) determined by expanding offset as an arithmetic expression and consisting of the number of characters determined by the arithmetic expression defined by length. In the second form, the remainder of the value is used. A negative offset counts backwards from the end of parameter. Note that one or more blanks is required in front of a minus sign to prevent the shell from interpreting the operator as :-. If parameter is ∗ or @, or is an array name indexed by ∗ or @, then offset and length refer to the array index and number of elements respectively. A negative offset is taken relative to one greater than the highest subscript for indexed arrays. The order for associate arrays is unspecified.

${parameter#pattern} ${parameter##pattern}

If the shell pattern matches the beginning of the value ofparameter, then the value of this expansion is the value of the parameter with the matched portion deleted; otherwise the value of this parameter is substituted. In the first form the smallest matching pattern is deleted and in the second form the largest matching pattern is deleted. When parameter is @, *, or an array variable with subscript @ or *, the substring operation is applied to each element in turn.

${parameter%pattern} ${parameter%%pattern}

If the shell pattern matches the end of the value of parameter, then the value of this expansion is the value of the parameter with the matched part deleted; otherwise substitute the value ofparameter. In the first form the smallest matching pattern is deleted and in the second

form the largest matching pattern is deleted. When parameter is @, *, or an array variable with subscript @ or *, the substring operation is applied to each element in turn.

${parameter/pattern/string} ${parameter//pattern/string} ${parameter/#pattern/string} ${parameter/%pattern/string}

Expands parameter and replaces the longest match of pattern with the given string. Each occurrence of \n in string is replaced by the portion of parameter that matches the n-th sub-pattern. In the first form, only the first occurrence of pattern is replaced. In the second form, each match for pattern is replaced by the givenstring. The third form restricts the pattern match to the beginning of the string while the fourth form restricts the pattern match to the end of the string. When string is null, the pattern will be deleted and the / in front of string 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, the string portion of word will be re-evaluated for each element.

The following parameters are automatically set by the shell:

# The number of positional parameters in decimal.

- Options supplied to the shell on invocation or by the set command.

? The decimal value returned by the last executed command.

$ The process number of this shell.

_ Initially, the value of _ (an underscore) is an absolute pathname of the shell or script being executed as passed in the environment. 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 with the 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 (See Type Variables below.).

! The process id or the pool name and job number of the last background command invoked or the most recent job put in the background with the bg built-in command. Background jobs started in a named pool will be in the formpool.number where pool is the pool name and number is the job number within that pool.

.sh.command When processing a DEBUG trap, this variable contains the current command line that is about to run.

.sh.edchar This variable contains the value of the keyboard character (or sequence of characters if the first character is an ESC, ASCII code 033) that has been entered when processing a KEYBD trap (see Key Bindings below). If the value is changed as part of the trap action, then the new value replaces the key (or key sequence) that caused the trap.

.sh.edcol The character position of the cursor at the time of the most recent KEYBD trap.

.sh.edmode The value is set to ESC when processing a KEYBD trap while in vi insert mode. (See Vi Editing Mode below.) Otherwise, .sh.edmode is null when processing a KEYBD trap.

.sh.edtext 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.

.sh.file The pathname of the file that contains the current command.

.sh.fun The name of the current function that is being executed.

.sh.level Set to the current function depth. This can be changed inside a DEBUG trap and will set the context to the specified level.

.sh.lineno Set during a DEBUG trap to the line number for the caller of each function.

.sh.match An indexed array which stores the most recent match and sub-pattern matches after conditional pattern matches that match and after variables expansions using the operators #, %, or /. The 0-th element stores the complete match and the i-th element stores the i-th submatch. The .sh.match variable becomes unset when the variable that has expanded is assigned a new value.

.sh.math Used for defining arithmetic functions (see Arithmetic evaluation below). and stores the list of user defined arithmetic functions.

.sh.name Set to the name of the variable at the time that a discipline function is invoked.

.sh.subscript Set to the name subscript of the variable at the time that a discipline function is invoked.

.sh.subshell The current depth for subshells and command substitution.

.sh.value Set to the value of the variable at the time that the set or append discipline function is invoked. When a user

defined arithmetic function is invoked, the value of .sh.value is saved and .sh.value is set to long double precision floating point.sh.value is restored when the function returns.

.sh.version 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 or function being executed.

OLDPWD The previous working directory set by the cd command.

OPTARG The value of the last option argument processed by the getopts built-in command.

OPTIND The index of the last option argument processed by the getopts built-in command.

PPID The process number of the parent of the shell.

PWD The present working directory set by the cd 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 assigning a numeric value to RANDOM.

REPLY This variable is set by the select statement and by the read built-in command when no arguments are supplied.

SECONDS Each time this variable is referenced, the number of seconds since shell invocation is returned. If this variable is assigned a value, then the value returned upon reference will be the value that was assigned plus the number of seconds since the assignment.

SHLVL An integer variable that is incremented each time the shell is invoked and is exported. If SHLVL is not in the environment when the shell is invoked, it is set to 1.

The following variables are used by the shell:

CDPATH The search path for the cd command.

COLUMNS If this variable is set, the value is used to define the width of the edit window for the shell edit modes and for printing select lists.

EDITOR If the VISUAL variable is not set, the value of this variable will be checked for the patterns as described with VISUAL below and the corresponding editing option will be turned on.

ENV If this variable is set, then parameter expansion, command substitution, and arithmetic substitution are performed on the value to generate the pathname of the script that will be executed when the shell is invoked interactively (seeInvocation below). This file is typically used for alias and function 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 ofENV begins with /./ or ././ the system wide initialization file will not be executed.

FCEDIT Obsolete name for the default editor name for the hist command. FCEDIT is not used when HISTEDIT is set.

FIGNORE A pattern that defines the set of filenames that will be ignored when performing filename matching.

FPATH The search path for function definitions. The directories in this path are searched for a file with the same name as 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 executed in the current environment. Unlike PATH, the current directory must be represented explicitly by "." rather than by adjacent ":" characters or a beginning or ending ":".

HISTCMD Number of the current command in the history file.

HISTEDIT Name for the default editor name for the hist command.

HISTFILE If this variable is set when the shell is invoked, then the value is the pathname of the file that will be used to store the command history (see Command Re-Entrybelow).

HISTSIZE If this variable is set when the shell is invoked, then the number of previously entered commands that are accessible by this shell will be greater than or equal to this number. The default is 512.

HOME The default argument (home directory) for the cd command.

IFS Internal field separators (normally space, tab, and newline) that are used to separate the results of command substitution or parameter expansion and to separate fields with the built-in command read. The first character of the IFSvariable is used to separate arguments for the "$∗" substitution (see Quotingbelow). Each single occurrence of an IFS character in the string to be split, that is not in the isspace character class, and any adjacent characters in IFS that are in the isspace character class, delimit a field. One or more characters in IFS that belong to the isspace character class, delimit a field. In addition, if the sameisspace character appears consecutively inside IFS, this character is treated as if it were not in the isspace class, so that if IFS consists of two tab characters, then

two adjacent tab characters delimit a null field.

JOBMAX This variable defines the maximum number running background jobs that can run at a time. When this limit is reached, the shell will wait for a job to complete before staring a new job.

LANG This variable determines the locale category for any category not specifically selected with a variable starting 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 character collation information.

LC_CTYPE This variable determines the locale category for character handling functions. It determines the character classes for pattern matching (see File Name Generationbelow).

LC_NUMERIC This variable determines the locale category for the decimal point character.

LINES If this variable is set, the value is used to determine the column length for printing select 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 file and the MAILPATH variable is not set, then the shell informs the user of arrival of mail in the specified file.

MAILCHECK This variable specifies how often (in seconds) the shell will check for changes in the modification time of any of the files specified by the MAILPATH or MAILvariables. The default value is 600 seconds. When the time has elapsed the 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 of any modifications to the specified files that 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 substitution with the variable $_ defined as the name of the file that has changed. The default message is "you have mail in $_.".

PATH The search path for commands (see Execution below). The user may not changePATH if executing under rksh (except in .profile).

PS1 The value of this variable is expanded for parameter expansion, command substitution, and arithmetic substitution to define the primary prompt string which by default is "$". The character ! in the

primary prompt string is replaced by the command number (see Command 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 string used within a select loop, by default "#? ".

PS4 The value of this variable is expanded for parameter evaluation, command substitution, and arithmetic substitution and precedes each line of an execution trace. By default, PS4 is "+". In addition when PS4 is unset, the execution trace prompt is also "+".

SHELL The pathname of the shell is kept in the environment. At invocation, if the basename of this variable is rsh, rksh, or krsh, then the shell becomes restricted. If it is pfsh or pfksh, then the shell becomes a profile shell.

TIMEFORMAT The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The % character introduces a format sequence that is expanded 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, including hours if greater than zero, minutes, and seconds of the form HHhMMmSS.FFs. The value of p determines whether or not the fraction is included. All other characters are output without change and a trailing newline 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 the read built-in command. The select compound command terminates afterTMOUT seconds when input is from a terminal. Otherwise, the shell will terminate if a line is not entered within the prescribed number of seconds while reading from a terminal. (Note that the shell can be compiled with a maximum bound for this value which cannot be exceeded.)

VISUAL If the value of this variable matches the pattern "*[Vv][Ii]*", then the vi option is turned on. If the value matches the pattern *gmacs*, the gmacs option is turned on. If the value matches the pattern *macs*, then the emacs option will be turned on. The value of VISUAL overrides the value of EDITOR.

The shell gives default values

to PATH, PS1, PS2, PS3, PS4, MAILCHECK, FCEDIT,TMOUT and IFS,

while HOME, SHELL, ENV, and MAIL are not set at all by the shell

(although HOME is set by login). On some systems MAIL and SHELL are also

set bylogin.

Field Splitting

After parameter expansion and command substitution, the results of

substitutions are scanned for the field separator characters (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 from parameters that

have no values or command substitutions with no output) are removed.

If the braceexpand (-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

and n1,n2,n3 are signed numbers and fmt is a format specified as used by printf.

In each case, fields are created by prepending the characters before the { and

appending the characters after the } to each of the strings generated by the

characters between the { and }. The resulting fields are checked to see if they

have any brace 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 and l2 must both be either upper case or both be lower

case characters in the C locale. In this case a field is created for each character

from l1 thrul2.

In the remaining forms, a field is created for each number starting at n1 and

continuing until it reaches n2 incrementing n1 by n3. The cases where n3 is not

specified behave as if n3 where 1 if n1<=n2 and -1 otherwise. If forms which

specify%fmt any format flags, widths and precisions can be specified

and fmt can end in any of the specifiers cdiouxX. For

example, {a,z}{1..5..3%02d}{b..c}x expands to the 8

fields, a01bx, a01cx, a04bx, a04cx, z01bx, z01cx, z04bx and z4cx.

File Name Generation

Following splitting, each field is scanned for the characters ∗, ?, (, and [ unless

the -foption has been set. If one of these characters appears, then the word is

regarded as a pattern. Each file name component that contains any pattern

character is replaced with a lexicographically sorted set of names that matches

the pattern from that directory. If no file name is found that matches the

pattern, then that component of the filename is left unchanged unless the pattern is prefixed with ∼(N) in which case it is removed as described below.

If FIGNORE is set, then each file name component that 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 component will be ignored unless the

first character of the pattern corresponding to this component is the

character . itself. Note, that for other uses 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 itself will match all files and zero or more directories and 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 any character lexically between the pair, inclusive. If the first character following the opening [ is a ! or ^ then any character not enclosed is matched. A - can be included in the character set by putting it as the first 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 primary collation weight (as defined by the current locale) as the character c. Within [ and ], [.symbol.] matches the collating symbol symbol.

A pattern-list is a list of one or more patterns separated from each other with 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:

?(pattern-list) Optionally matches any one of the given patterns.

*(pattern-list) Matches zero or more occurrences of the given patterns.

+(pattern-list) Matches one or more occurrences of the given patterns.

{n}(pattern-list)

Matches n occurrences of the given patterns.

{m,n}(pattern-list)

Matches from m to n occurrences of the given patterns. If m is omitted, 0 will be used. If n is omitted at least m occurrences will be matched.

@(pattern-list) Matches exactly one of the given patterns.

!(pattern-list) Matches anything except one of the given patterns.

By default, each pattern (or sub-pattern) will match the longest string possible

consistent with generating the longest overall match. If more than one match is

possible, the one starting closest to the beginning of the string will be chosen.

However, for each of the above compound patterns a "-" can be inserted in front

of the( to cause the shortest match to the specified pattern-list to be used.

When pattern-list is contained within parentheses, the backslash character \ is

treated specially even when inside a character class. All ANSI-C character

escapes are recognized and match the specified character. In addition the

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 that can be used to

matchnested character expressions. Each pattern-pair is a two character sequence which cannot contain & or ⎪. The first pattern-pair specifies the

starting and ending characters for the match. Each subsequent pattern-

pair represents the beginning and ending characters of a nested group that will

be skipped over when counting starting and ending character matches. The

behavior is unspecified when the first character of apattern-pair is alpha-numeric

except for the following:

D Causes the ending character to terminate the search for this pattern without finding 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 character causing all characters to be ignored when looking for a match.

Q Causes the ending character to be interpreted as a quote character causing all characters other than any escape character to be ignored when 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 ( within the pattern. The sequence \n, where n is a single digit

and \n comes after the 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-list can be omitted. Unlike the other compound

patterns, these sub-patterns are not counted in the numbered sub-

patterns. :pattern-list must be omitted for options F, G, N , and V below. If

options is present, it can consist of one or more of the following:

+ Enable the following options. This is the default.

- Disable the following options.

E The remainder of the pattern uses extended regular expression syntax like the egrep command.

F The remainder of the pattern uses fgrep expression syntax.

G The remainder of the pattern uses basic regular expression syntax like the grep 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 is used with file name generation, and no matches occur, the file pattern expands to the empty string.

X The remainder of the pattern uses augmented regular expression syntax like the xgrepcommand.

P The remainder of the pattern uses perl regular expression syntax. Not all perl regular expression syntax is currently implemented.

V The remainder of the pattern uses System V regular expression syntax.

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 for K style patterns.

r Right anchor the pattern. This is the default for K style patterns.

If both options and :pattern-list are specified, then the options apply only

to pattern-list. Otherwise, these options remain in effect until they are disabled by a subsequent∼(...) or at the end of the sub-pattern containing ∼(...).

Quoting

Each of the metacharacters listed earlier (see Definitions above) has a special

meaning to the shell and causes termination of a word unless quoted. A

character may be quoted (i.e., made to stand for itself) by preceding it with a \.

The pair \newline 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 string except for the following:

\0 Causes the remainder of the string to be ignored.

\E Equivalent to the escape character (ASCII 033),

\e Equivalent to the escape character (ASCII 033),

\cx Expands to the character control-x.

\C[.name.] 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 ignored in the "C" or "POSIX" locale, and may cause the 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 value or as a file name. However, when used as a command argument, "$∗" is equivalent to

"$1d$2d...", where d 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 ".

The special meaning of reserved words or aliases can be removed by quoting

any character of the reserved word. The recognition of function names or built-in

command names listed below cannot be altered by quoting them.

Arithmetic Evaluation

The shell performs arithmetic evaluation for arithmetic substitution, to evaluate

an arithmetic command, to evaluate an indexed array subscript, and to evaluate

arguments to the built-in commands shift and let. Evaluations are performed

using double precision floating point arithmetic or long double precision floating

point for systems that provide this data type. Floating point constants follow the

ANSI-C programming language floating point conventions. The floating point

constants Nanand Inf can be use to represent "not a number" and infinity

respectively. Integer constants follow the ANSI-C programming language integer

constant conventions although only single byte character constants are

recognized and character casts are not recognized. In addition constants can be

of the form [base#]n where base is a decimal number between two and sixty-

four representing the arithmetic base and n is a number in that base. The digits

above 9 are represented by the lower case letters, the upper case letters, @,

and _ respectively. For bases less than or equal to 36, upper and lower case

characters can be used interchangeably.

An arithmetic expression uses the same syntax, precedence, and associativity of

expression as the C language. All the C language operators that apply to floating

pointquantities 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 variable or 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 expression without using the parameter expansion syntax.

When a variable is referenced, its value is evaluated as an arithmetic expression.

Any of the following math library functions that are in the C math library can be

used within an arithmetic expression: • abs • acos • acosh • asin • asinh • atan • atan2 • atanh • cbrt • ceil • copysign • cos • cosh • erf • erfc • exp • exp2 • expm1 • fabs • fpclassify • fdim • finite • floor • fma • fmax • fmin • fmod • hypot

• ilogb • int • isfinite • sinf • isnan • isnormal • issubnormal • issubordered • iszero • j0 • j1 • jn • lgamma • log • log10 • log2 • logb • nearbyint • nextafter • nexttoward • pow • remainder • rint • round • scanb • signbit • sin • sinh • sqrt • tan • tanh • tgamma • trunc • y0 • y1 • yn

In addition, arithmetic functions can be defined as shell functions with a variant

of the function name syntax, function .sh.math.name ident ... { list ;}

where name is the function name used in the arithmetic expression and each

identifier,ident is a name reference to the long double precision floating

point argument. The value of .sh.value when the function returns is the value of

this function. User defined functions can take up to 3 arguments and override C

math library functions.

An internal representation of a variable as a double precision floating point can

be specified with the -E [n], -F [n], or -X [n] option of the typeset special built-

in command. The -E option causes the expansion of the value to be represented

using scientific notation when it is expanded. The

optional option argument n defines the number of significant figures. The -F option causes the expansion to be represented as a floating decimal number

when it is expanded. The -X option cause the expansion to be represented using

the %a format defined by ISO C-99. The optional option argument n defines the

number of places after the decimal (or radix) point in this case.

An internal integer representation of a variable can be specified with the -i [n]

option of the typeset special built-in command. The optional option

argument n 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 each assignment to a variable

with the -E, -F, -X, or -i attribute. Assigning a floating point number to a

variable whose type is an integer causes the fractional part to be truncated.

Prompting

When used interactively, the shell prompts with the value of PS1 after expanding

it for parameter expansion, command substitution, and arithmetic 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 newline is typed and further input is needed to complete a command, then the

secondary prompt (i.e., the value of PS2) is issued.

Conditional Expressions

A conditional expression is used with the [[ compound command to test

attributes of files and to compare strings. Field splitting and file name generation

are not performed on the words between [[ and ]]. Each expression can be

constructed from one or more of the following unary or binary expressions:

"string True", if string is not null.

-a file Same as -e below. This is obsolete.

-b file True, if file exists and is a block special file.

-c file True, if file exists and is a character special file.

-d file True, if file exists and is a directory.

-e file True, if file exists.

-f file True, if file exists and is an ordinary file.

-g file True, if file exists and it has its setgid bit set.

-k file True, if file exists and it has its sticky bit set.

-nstring True, if length of string is non-zero.

-o ?option True, if option named option is a valid option name.

-ooption True, if option named option is on.

-p file True, if file exists and is a fifo special file or a pipe.

-r file True, if file exists and is readable by current process.

-s file True, if file exists and has size greater than zero.

-tfildes True, if file descriptor number fildes is open and associated with a terminal device.

-u file True, if file exists and it has its setuid bit set.

-vname True, if variable name is a valid variable name and is set.

-w file True, if file exists and is writable by current process.

-x file True, if file exists and is executable by current process. If file exists and is a directory, then true if the current process has permission to search in the directory.

-zstring True, if length of string is zero.

-L file True, if file exists and is a symbolic link.

-h file True, if file exists and is a symbolic link.

-N file True, if file exists and the modification time is greater than the last access time.

-O file True, if file exists and is owned by the effective user id of this process.

-G file True, if file exists and its group matches the effective group id of this process.

-Rname True if variable name is a name reference.

-S file True, if file exists and is a socket.

file1 -nt file2 True, if file1 exists and file2 does not, or file1 is newer than file2.

file1 -ot file2 True, if file2 exists and file1 does not, or file1 is older than file2.

file1 -ef file2 True, if file1 and file2 exist and refer to the same file.

string==pattern True, if string matches pattern. Any part of pattern 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, if string does not match pattern. When the string matches the pattern the.sh.match array variable will contain the match and sub-pattern matches.

string=∼ ere True if string matches the pattern ∼(E)ere where ere is an extended regular expression.

string1<string2 True, if string1 comes before string2 based on ASCII value of their characters.

string1>string2 True, if string1 comes after string2 based on ASCII value of their characters.

The following obsolete arithmetic comparisons are also permitted:

exp1 -eq exp2 True, if exp1 is equal to exp2.

exp1 -ne exp2 True, if exp1 is not equal to exp2.

exp1 -lt exp2 True, if exp1 is less than exp2.

exp1 -gt exp2 True, if exp1 is greater than exp2.

exp1 -le exp2 True, if exp1 is less than or equal to exp2.

exp1 -ge exp2 True, if exp1 is greater than or equal to exp2.

In each of the above expressions, if file is of the form /dev/fd/n, where n is an

integer, then the test is applied to the open file whose descriptor number is n.

A compound expression can be constructed from these primitives by using any of

the following, listed in decreasing order of precedence.

(expression) True, if expression is true. Used to group expressions.

! expression True if expression is false.

expression1 && expression2 True, if expression1 and expression2 are both

true.

expression1 ⎪⎪ expression2 True, if either expression1 or expression2 is true.

Input/Output

Before a command is executed, its input and output may be redirected using a

special notation interpreted by the shell. The following may appear anywhere in

a simple-command or may precede or follow a command and are not passed on

to the invoked command. Command substitution, parameter expansion, and

arithmetic substitution occur before word or digit is used except as noted below.

File name generation occurs only if the shell is interactive and the pattern

matches a single file. Field splitting is not performed.

In each of the following redirections, if file is of the

form /dev/sctp/host/port,/dev/tcp/host/port, or /dev/udp/host/port,

where host is a hostname or host address, and port is a service given by name

or an integer port number, then the redirection attempts to make a tcp, sctp

or udp connection to the corresponding socket.

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

<word Use file word as standard input (file descriptor 0).

>word Use file word as standard output (file descriptor 1). If the file does not exist then it is created. If the file exists, and the noclobber option is on, this causes an error; otherwise, it is truncated to zero length.

>|word Same as >, except that it overrides the noclobber option.

>;word Write output to a temporary file. If the command completes successfully, rename it toword, otherwise, delete the temporary file. >;word cannot be used with the execbuilt-in.

>>word Use file word 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 file word for reading and writing as 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 built-in.

<<[-]word The shell input is read up to a line that is the same as word after any

quoting has been removed, or to an end-of-file. No parameter substitution, command substitution, arithmetic substitution or file name generation is performed on word. The resulting document, called a here-document, becomes the standard input. If any character of word is quoted, then no interpretation is placed upon the characters of the document; otherwise, parameter expansion, command substitution, and arithmetic substitution occur, \newline is ignored, and \ must be used to quote the characters \, $, '. If - is appended to <<, then all leading tabs are stripped from word and from the document. If # is appended to <<, then leading spaces and tabs will be stripped off the first line of the document and up to an equivalent indentation will be stripped from the remaining lines and from word. A tab stop is assumed to occur at every 8 columns for the purposes of determining the indentation.

<<<word A short form of here-document in which word becomes the contents of the here-document after any parameter expansion, command substitution, and arithmetic substitution occur.

<&digit The standard input is duplicated from file descriptor digit. Similarly for the standard output using >&digit.

<&digit- The file descriptor given by digit 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 expression expr and position file descriptor 0 to the resulting value bytes from the start of the file. The variables CUR and EOF evaluate to the current offset and end-of-file offset respectively when evaluating expr.

>#((offset)) The same as <# except applies to file descriptor 1.

<#pattern Seeks forward to the beginning of the next line containing pattern.

<##pattern The same as <# except that the portion of the file that is skipped is copied to standard output.

If one of the above is preceded by a digit, with no intervening space, then the

file descriptor number referred to is that specified by 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 greater than 10 will be selected by the shell and stored in the

variable varname. If >&- or the any of the ># and <# forms is preceded

by {varname} the value of varname defines the file descriptor to close or

position. For example: ... 2>&1

means file descriptor 2 is to be opened for writing as a duplicate of file descriptor

1 and exec {n}<file

means open file named file for reading and store the 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 file fname. It then associates file descriptor

2 with the file associated with file descriptor 1 (i.e. fname). If the order of

redirections were reversed, file descriptor 2 would be associated with the

terminal (assuming file descriptor 1 had been) and then file descriptor 1 would

be associated with file fname.

If a command is followed by & and job control is not active, then the default

standard input for the command is the empty file /dev/null. Otherwise, the

environment for the execution of a command contains the file descriptors of the

invoking shell as modified by input/output specifications.

Environment

The environment is a list of name-value pairs that is passed to an executed

program in the same way as a normal argument list. The names must be

identifiers and the values are character strings. The shell interacts with the

environment in several ways. On invocation, the shell scans the environment and

creates a variable for each name found, giving it the corresponding value and

attributes and marking it export. Executed commands inherit the environment. If

the user modifies the values of these variables or creates new ones, using

the export or typeset -x commands, they become part of the environment. The

environment seen by any executed command is thus composed of any name-

value pairs originally inherited by the shell, whose values may be modified by

the current shell, plus any additions which must be noted in export ortypeset -x commands.

The environment for any simple-command or function may be augmented by

prefixing it with one or more variable assignments. A variable assignment

argument is a word of the form identifier=value. Thus: TERM=450 cmd args

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

are equivalent (as far as the above execution of cmd is concerned except for

special built-in commands listed below - those that are preceded 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 following first

printsa=b c and then c: echo a=b c set -k echo a=b c

This feature is intended for use with scripts written for early versions of the shell

and its use in new scripts is strongly discouraged.

Functions

For historical reasons, there are two ways to define functions,

the name() syntax and the function name syntax, described in

the Commands 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 arguments passed as positional parameters.

(See Execution below.)

Functions defined by the function name syntax and called by name execute in

the same process as the caller and share all files and present working directory

with the caller. Traps caught by the caller are reset to their default action inside

the function. A trap condition that is not caught or ignored by the function

causes the function to terminate and the condition to be passed on to the caller.

A trap on EXIT set inside a function is executed in the environment of the caller

after the function completes. Ordinarily, variables are shared between the calling

program and the function. However, the typeset special built-in command used

within a function defines local variables whose scope includes the current

function. They can be passed to functions that they call in the variable

assignment list that precedes the call or as arguments passed as name

references. Errors within functions return control to the caller.

Functions defined with the name() syntax and functions defined with the

function name syntax that are invoked with the . special built-in are executed in

the caller's environment and share all variables and traps with the caller. Errors

within these function executions cause the script that contains them to abort.

The special built-in command return is used to return from function calls.

Function names can be listed with the -f or +f option of the typeset special

built-in command. The text of functions, when available, will also be listed with -f. Functions can be undefined with the -f option of the unset special built-in

command.

Ordinarily, functions are unset when the shell executes a shell script. Functions

that need to be defined across separate invocations of the shell should be placed

in a directory and the FPATH variable should contain the name of this directory.

They may also be specified in the ENV file.

Discipline Functions

Each variable can have zero or more discipline functions associated with it. The

shell initially understands the discipline names get, set, append, and unset but

can be added when defining new types. On most systems others can be added at

run time via the C programming interface extension provided by

the builtin built-in utility. If theget discipline is defined for a variable, it is

invoked whenever the given variable is referenced. If the variable .sh.value is

assigned a value inside the discipline function, the referenced variable will

evaluate to this value instead. If the set discipline is defined for a variable, it is

invoked whenever the given variable is assigned a value. If

the append discipline is defined for a variable, it is invoked whenever a value is

appended to the given variable. The variable .sh.value is given the value of the

variable before invoking the discipline, and the variable will be assigned the

value of.sh.value after the discipline completes. If .sh.value is unset inside the

discipline, then that value is unchanged. If the unset discipline is defined for a

variable, it is invoked whenever the given variable is unset. The variable will not

be unset unless it is unset explicitly from 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 the set 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 is no variable of this name, is equivalent to the command

substitution ${ var.name;}.

Name Spaces

Commands and functions that are executed as part of the list of a namespace

command that modify variables or create new ones, create a new variable whose

name is the name of the name space as given by identifier preceded by ".." When a variable whose name is name is referenced, it is first searched for

using .identifier.name. Similarly, a function defined by a command in the

namespace list is created using the name space name preceded by a ".".

When the list of a namespace command contains a namespace command, the

names of variables and functions that are created consist of the variable or

function name preceded by the list of identifiers each preceded by ".".

Outside of a name space, a variable or function created inside a name space can

be referenced by preceding it with the name space name.

By default, variables staring with .sh are in the sh name space.

Type Variables

Typed variables provide a way to create data structure and objects. A type can

be defined either by a shared library, by the enum built-in command described

below, or by using the new -T option of the typeset built-in command. With

the -T option of typeset, 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 variable assignment and these

become discipline functions for this type and can be invoked or redefined by

each instance of the type. The function name create is treated specially. It is

invoked for each instance of the type that is created but is not inherited and

cannot be redefined for each instance.

When a type is defined a special built-in command of that name is added. These

built-ins are declaration commands and follow the same expansion rules as all

the special built-in commands defined below that are preceded by ††. These

commands can subsequently be used inside further type definitions. The man

page for these commands can be generated by using the --man option or any of

the other -- options described with getopts. The -r, -a, -A, -h, and -S options

of typeset are permitted with each of these new built-ins.

An instance of a type is created by invoking the type name followed by one or

more instance names. Each instance of the type is initialized with a copy of the

sub-variables except 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 also define new

discipline functions of the same names as those defined by the type definition as

well as any standard 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-variable to be a required sub-variable. Whenever

an instance of a type is created, all required sub-variables must be specified.

These sub-variables become readonly in each instance.

When unset 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

with the type. Invoking unset on a type instance not contained within another

type deletes all sub-variables and the variable itself.

A type definition can be derived from another type definition by defining the first

sub-variable name as _ and defining its type as the base type. Any remaining

definitions will be additions and modifications that 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 will no longer be accessible.

The typeset command with the -T and no option argument or operands will

write all the type definitions to standard output in a form that that can be read in

to create all they types.

Jobs

If the monitor option of the set command is turned on, an interactive shell

associates a job with each pipeline. It keeps a table of current jobs, printed by

the jobscommand, and assigns them small integer numbers. When a job is

started asynchronously with &, the shell prints a line which looks like: [1] 1234

indicating that the job which was started asynchronously was job number 1 and

had one (top-level) process, whose process id was 1234.

This paragraph and the next require features that are not 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 the bgcommand, or run some other commands and then

eventually bring the job back into the foreground with the foreground

command fg. A ^Z takes effect immediately and is like an interrupt in that

pending output and unread input are discarded when it is typed.

A job being run in the background will stop if it tries to read from the terminal.

Background jobs are normally allowed to produce output, but this can be

disabled by giving the command stty tostop. If you set this tty option, then

background jobs will stop when they try to produce output like they do when

they try to read input.

A job pool is a collection of jobs started with list & associated with a name.

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 job or by one of the following:

%number The job with the given number.

pool All the jobs in the job pool named by pool.

pool.number The job number number in the job pool named by pool.

%string Any job whose command line begins with string.

%?string Any job whose command line contains string.

%% Current job.

%+ Equivalent to %%.

%- Previous job. In addition, unless noted otherwise, wherever a job can be specified, the name of a background job pool can be used to represent all the jobs in that pool.

The shell learns immediately whenever a process changes state. It normally

informs you whenever a job becomes blocked so that no further progress is

possible, but only just before it prints a prompt. This is done so that it does not

otherwise disturb your work. The notify option of the set command causes the

shell to print these job change messages as soon as they occur.

When the monitor option is on, each background job that completes triggers

any trap set for CHLD.

When you try to leave the shell while jobs are running or stopped, you will be

warned that 'You have stopped(running) jobs.' You may use the jobs command

to see what they are. If you immediately try to exit again, the shell will not warn

you a second time, and the stopped jobs will be terminated. When a login shell

receives a HUP signal, it sends a HUP signal to each job that has not been

disowned with the disownbuilt-in command described below.

Signals

The INT and QUIT signals for an invoked command are ignored if the command

is followed by & and the monitor option is not active. Otherwise, signals have

the values inherited by the shell from its parent (but see also the trap built-in

command below).

Execution

Each time a command is read, the above substitutions are carried out. If the

command name matches one of the Special Built-in Commands listed below, it is

executed within the current shell process. Next, the command name is checked

to see if it matches a user defined function. If it does, the positional parameters

are saved and then reset to the arguments of the function call. A function is also

executed in the current shell process. When the function completes or issues

a return, the positional parameter list is restored. For functions defined with

the function name syntax, any trap set on EXIT within the function is executed.

The exit value of a function is the value of the last command executed. If a

command name is not a special built-in command or a user defined function, but

it is one of the built-in commands listed below, it is executed in the current shell

process.

The shell variables PATH followed by the variable FPATH defines the list of

directories to search for the command name. Alternative directory names are

separated by a colon (:). The default path

is /bin:/usr/bin: (specifying /bin, /usr/bin, and the current directory in that

order). The current directory can be specified by two or more adjacent colons, or

by a colon at the beginning or end of the path list. If the command name

contains a /, then the search path is not used. Otherwise, each directory in the

list of directories defined by PATH and FPATH is checked in order. If the

directory being searched is contained in FPATH and contains a file whose name

matches the command being searched, then this file is loaded into the current

shell environment as if it were the argument to the . command except that only

preset aliases are expanded, and a function of the given name is executed as

described above.

If this directory is not in FPATH the shell first determines whether there is a

built-in version of a command corresponding to a given pathname and if so it is

invoked in the current process. If no built-in is found, the shell checks for a file

named .paths in this directory. If found and there is a line of the

form FPATH=path where path names an existing directory then that directory is

searched after immediately after the current directory as if it were found in

the FPATH variable. If path does not begin with /, it is checked for relative to

the directory being searched.

The .paths file is then checked for a line of the

form PLUGIN_LIB=libname "[ :libname ] ...". Each library named

by libname will be searched for as if it were an option argument to builtin -f, and if it contains a built-in of the specified name this will be executed instead of

a command by this name. Any built-in loaded from a library found this way will

be associated with the directory containing the .paths file so it will only execute

if not found in an earlier directory.

Finally, the directory will be checked for a file of the given name. If the file has

execute permission but is not an a.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 command file doesn't have read

permission, or if the setuid and/or setgid bits are set on the file, then the shell

executes an agent whose job it is to set up the permissions and execute the shell

with the shell command file passed down as an open file. If the .paths contains

a line of the form name=value in the first or second line, then the environment

variable name is modified by prepending the directory specified by value to the

directory list. If value is not an absolute directory, then it specifies a directory

relative to the directory that the executable was found. If the environment

variable name does not already exist it will be added to the environment list for

the specified command. A parenthesized command is executed in a sub-shell

without removing non-exported variables.

Command Re-Entry

The text of the last HISTSIZE (default 512) commands entered from

a terminal device is saved in a history file. The file $HOME/.sh_history is used

if the HISTFILEvariable is not set or if the file it names is not writable. A shell

can access the commands of all interactive shells which use the same

named HISTFILE. The built-in command hist is used to list or edit a portion of

this file. The portion of the file to be edited or listed can be selected by number

or by giving the first character or characters of the command. A single command

or range of commands can be specified. If you do not specify an editor program

as an argument to hist then the value of the variableHISTEDIT is used.

If HISTEDIT is unset, the obsolete variable FCEDIT is used. IfFCEDIT is not

defined, then /bin/ed is used. The edited command(s) is printed and re-

executed upon leaving the editor unless you quit without writing. The -s option

(and in obsolete versions, the editor name -) is used to skip the editing phase

and to re-execute the command. In this case a substitution parameter of the

form old=new can be used to modify the command before execution. For

example, with the preset alias r, which is aliased to ′hist -s′, typing 'r bad=good c' will re-execute the most recent command which starts with the

letter c, replacing the first occurrence of the string badwith the string good.

In-Line Editing Options

Normally, each command line entered from a terminal device is simply typed

followed by a newline ('RETURN' or 'LINE FEED'). If either the emacs, gmacs,

or vi option is active, the user can edit the command line. To be in either of

these edit modes set the corresponding option. An editing option is automatically

selected each time theVISUAL or EDITOR variable is assigned a value ending in

either of these option names.

The editing features require that the user's terminal accept 'RETURN' as carriage

return without line feed and that a space (' ') must overwrite the current

character on the screen.

Unless the multiline option is on, the editing modes implement a concept where

the user is looking through a window at the current line. The window width is the

value ofCOLUMNS if it is defined, otherwise 80. If the window width is too small

to display the prompt and leave at least 8 columns to enter input, the prompt is

truncated from the left. If the line is longer than the window width minus two, a

mark is displayed at the end of the window to notify the user. As the cursor

moves and reaches the window boundaries the window will be centered about

the cursor. The mark is a > (<, *) if the line extends on the right (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

match to begin at the first character in the line. Each of the edit modes has an

operation to list the files or 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 commands defined by the PATH variable that could match the

partial word is displayed. Otherwise, the list of files that match the given word is

displayed. If the partially entered word does not contain any file expansion

characters, a * is appended before generating these lists. After displaying the

generated list, the input line is redrawn. These operations are called command

name listing and file name listing, respectively. There are additional operations,

referred to as command name completion and file name completion, which

compute the list of matching commands or files, but instead of printing the list,

replace the 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 is appended if the file is not a directory. Otherwise, the longest common

prefix for all the matching files replaces the word. For command name

completion, only the portion of the file names after the last / are used to find

the longest command prefix. If only a single name matches this prefix, then the

word is replaced with the command name followed by a space. When using a tab

for completion that does not yield a unique match, a subsequent tab will provide

a numbered list of matching alternatives. A specific selection can be made by

entering the selection number followed by a tab.

Key Bindings

The KEYBD trap can be used to intercept keys as they are typed and change the

characters that are actually seen by the 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 which generated the trap. Changing the value

of .sh.edchar in the trap action causes the shell to behave as if the new value

were entered from the keyboard rather than the original value.

The variable .sh.edcol is set to the input column number of the cursor at the

time of the input. The variable .sh.edmode is set to ESC when in vi insert mode

(see below) and is null otherwise. By prepending ${.sh.editmode} to a value

assigned to.sh.edchar it will cause the shell to change to control mode if it is

not already in this mode.

This trap is not invoked for characters entered as arguments to editing

directives, or while reading input for a character search.

Emacs Editing Mode

This mode is entered by enabling either the emacs or gmacs option. The only

difference between these two modes is the way they handle ^T. To edit, the

user moves the cursor to the point needing correction and then inserts or deletes

characters or words as needed. All the editing commands are control characters

or escape sequences. The notation for control characters is caret (^) followed by

the character. For example, ^F is the notation for control-F. This is entered by

depressing 'f' while holding down the 'CTRL' (control) key. The 'SHIFT' key is

not depressed. (The notation^? indicates the DEL (delete) key.)

The notation for escape sequences is M- followed by a character. For

example, M-f(pronounced Meta f) is entered by depressing ESC (ASCII 033)

followed by 'f'. (M-Fwould be the notation for ESC followed by 'SHIFT' (capital)

'F'.)

All edit commands operate from any place on the line (not just at the beginning).

Neither the 'RETURN' nor the 'LINE FEED' key is entered 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. (The emacs editor's idea of a word is a string of characters consisting 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 character char on current line.

M-^]char

Move cursor backward to character char on current line.

^X^X Interchange the cursor and mark.

erase (User defined erase character as defined by the stty command, usually ^H or #.) Delete previous character.

lnext (User defined literal next character as defined by the stty command, or ^V if not defined.) Removes the next character's editing 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 character and advance the cursor in emacsmode. Transpose two previous characters in gmacs 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 the current cursor position, then delete from given position up to the cursor. If preceded by a numerical parameter whose value is greater than the current cursor position, then delete from cursor up to given 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 defined by the stty command, usually ^G or @.) Kill the entire current line. If two kill characters are entered in succession, all kill characters from then on cause a line feed.

^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 only if the current line is null.

^P Fetch previous command. Each time ^P is entered the 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 with string set to the contents of the current line. Otherwise, it is equivalent 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 entered the next command line forward in time is accessed.

M-[B Equivalent to ^N.

^Rstring Reverse search history for a previous command line containing string. If a parameter of zero is given, the search is forward. string is terminated by a 'RETURN' or 'NEW LINE'. Ifstring is preceded by a ^, the matched line must begin with string. If string is omitted, then the next command line containing the most recent string is accessed. In this case a parameter of zero reverses the direction of the search.

^O Operate - Execute the current line and fetch the next line relative to current line from the history file.

M-digits (Escape) Define numeric parameter, the digits are 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 and M-^H.

M-letter Soft-key - Your alias list is searched for an alias by the name _letter and if an alias of this name is defined, its value will be inserted on the input queue. The letter must not be one of the above meta-functions.

M-[letter

Soft-key - Your alias list is searched for an alias by the name __letter and if an alias of this name is defined, its value 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 inserted on the line. If preceded by a numeric parameter, the value of this parameter determines which word to insert rather than the last word.

M-_ Same as M-..

M-* Attempt file name generation on the current word. An asterisk is appended if the word doesn't match any file or contain any special pattern 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 will behave as if M-= were

entered. If no match is found or entered after space, a tab is inserted.

M-= If not preceded by a numeric parameter, it generates the list of matching commands or file names as described above. Otherwise, the word under the cursor is replaced by the item corresponding to the value of the numeric parameter from 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 and interrupt (normally^?) characters may be entered in a command line or in a search string if preceded by a\. The \ removes the next character's editing features (if any).

M-^V Display version of the shell.

M-# If the line does not begin with a #, a # is inserted at the beginning of the line and after each newline, 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 newline is also deleted.

Vi Editing Mode

There are two typing modes. Initially, when you enter a command you are in the

input mode. To edit, the user enters control mode by typing ESC (ASCII code

033) and moves the cursor to the point needing correction and then inserts or

deletes characters or words as needed. Most control commands accept an

optional repeat count prior to the command.

When in vi mode on most systems, canonical processing is initially enabled and

the command will be echoed again if the speed is 1200 baud or greater and it

contains any control characters or less than one second has elapsed since the

prompt was printed. The ESC character terminates canonical processing for the

remainder of the command and the user can then modify the command line. This

scheme has the advantages of canonical processing with the type-ahead echoing

of raw mode.

If the option viraw is also set, the terminal will always have canonical

processing disabled. This mode is implicit for systems that do not support two

alternate end of line delimiters, and may be helpful for certain terminals.

By default the editor is placed into "Input" edit mode.

Input Edit Commands:

erase (User defined erase character as defined by the stty command, usually ^H or #.) Delete previous character.

^W Delete the previous blank-separated word. On some systems the viraw option may be required for this to work.

eof As the first character of the line causes the shell to terminate unless the ignoreeof option is set. Otherwise this character is ignored.

lnext (User defined literal next character as defined by the stty or ^V if not defined.) Removes the next character's editing features (if any). On some systems the viraw option may be required for this to work.

\ Escape the next erase or kill character.

^I tab

Attempts command or file name completion as described above and returns to input mode. If a partial completion occurs, repeating this will behave as if = were entered from control mode. If no match is found or entered after space, a tab is inserted.

Motion Edit Commands (these commands will move the cursor):

[count]l Cursor forward (right) one character.

[count][C Cursor forward (right) one character.

[count]w Cursor forward one alpha-numeric word.

[count]W Cursor to the beginning of the next word that follows a blank.

[count]e Cursor to end of word.

[count]E Cursor to end of the current blank delimited word.

[count]h Cursor backward (left) one character.

[count][D Cursor backward (left) one character.

[count]b Cursor backward one word.

[count]B Cursor to preceding blank separated word.

[count]⎪ Cursor to column count.

[count]fc Find the next character c in the current line.

[count]Fc Find the previous character c in the current line.

[count]tc Equivalent to f followed by h.

[count]Tc Equivalent to F followed by l.

[count]; Repeats count times, the last single character find command (f, F, t, or T).

[count], Reverses the last single character find command count 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 first occurrence of one of the above characters first.

Search Edit Commands (commands that access your command history):

[count]k Fetch previous command. Each time k is entered the previous command back in time is accessed.

[count]- Equivalent to k.

[count][A If cursor is at the end of the line it is equivalent to / with string set to the contents of the current line. Otherwise, it is equivalent to k.

[count]j Fetch next command. Each time j is entered the next command forward in time is accessed.

[count]+ Equivalent to j.

[count][B Equivalent to j.

[count]G The command number count is fetched. The default is the least recent history command.

/string Search backward through history for a previous command containing string. String is terminated by a 'RETURN' or 'NEW LINE'. If string is preceded by a ^, the matched line must begin with string. 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.

Vi Mode Text Modification Edit Commands (these commands will modify the

line):

a Enter input mode and enter text after the current character.

A Append text to the end of the line. Equivalent to $a.

[count]cmotion c[count]motion

Delete current character through the character that motion would move the cursor to and enter input mode. If motion is c, the entire line will be deleted and input mode entered.

C Delete the current character through the end of line and enter input mode. Equivalent to c$.

S Equivalent to cc.

[count]s Replace characters under the cursor in input mode.

D Delete the current character through the end of line. Equivalent to d$.

[count]dmotion d[count]motion

Delete current character through the character that motion would move to. If motion is d, 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 to 0i.

[count]P Place the previous text modification before the cursor.

[count]p Place the previous text modification after the cursor.

R Enter input mode and replace characters on the screen with characters you type overlay fashion.

[count]rc Replace the count character(s) starting at the current cursor position with c, and advance the cursor.

[count]x Delete current character.

[count]X Delete preceding character.

[count]. Repeat the previous text modification command.

[count]∼ Invert the case of the count character(s) starting at the current cursor position and advance the cursor.

[count]_ Causes the count word of the previous command to be appended and input mode entered. The last word is used if count is omitted.

* Causes an * to be appended to the current word and file name generation attempted. If no match is found, it plays an audio bell. Otherwise, the word is replaced by the matching pattern and input mode is entered.

\ Command or file name completion as described above.

Other Miscellaneous Vi Mode Edit Commands:

[count]ymotion y[count]motion

Yank current character through character that motion 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 to y$.

u Undo the last text modifying command.

U Undo all the text modifying commands performed on the line.

[count]v Returns the command hist -e ${VISUAL:-${EDITOR:-vi}} count in the input buffer. If count 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 after inserting a # in front of each line in the command. Useful for causing the current line to be inserted in the history as a comment and uncommenting previously commented commands in the history file.

[count]= If count is not specified, it generates the list of matching commands or file names as described above. Otherwise, the word under the the cursor is replaced by the count 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 an alias by the name _letter and if an alias of this name is defined, its value 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 1 and the exit status, when there is no syntax error, is zero. Except

for :,true, false, echo, newgrp, and login, all built-in commands accept -- to

indicate end of options. They also interpret the option --man as a request to

display the man page onto standard error and -? as a help request which prints

a usage message on standard error. Commands that are preceded by one or two

† symbols are special built-in commands and are treated specially in the

following ways: 1. Variable assignment lists preceding the command remain in effect when the

command completes. 2. I/O redirections are processed after variable assignments. 3. Errors cause a script that contains them to abort. 4. They are not valid function names. 5. Words following a command preceded by †† that are in the format of a

variable assignment are expanded with the same rules as a variable assignment. This means that tilde substitution is performed after the = sign and field splitting and file name generation are not performed. These are called declaration built-ins.

† : [ arg ... ] The command only expands parameters.

† . name [ arg ... ] If name is a function defined with the function name reserved word syntax, the function is executed in the current environment (as if it had been defined with the name() syntax.) Otherwise if name refers to a file, the file is read in its entirety and the commands are executed in the current shell environment. The search path specified by PATH is used to find the directory containing the file. If any arguments arg are given, they become the positional parameters while processing the .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 aliases in the formname=value on standard output. The -p option causes the word alias to be inserted before each one. When one or more arguments are given, an alias is defined for each

name whose value is given. A trailing space in value causes the next word to be checked for alias substitution. The obsolete -t option is used to set and list tracked aliases. The value of a tracked alias is the full pathname corresponding to the given name. The value becomes undefined when the value of PATH is reset but the alias remains tracked. Without the -t option, for each name in the argument list for which no value is given, the name and value of the alias is printed. The obsolete -x option has no effect. The exit status is non-zero if a name is given, but no value, and no alias has been defined for the name.

bg [ job... ] (This command exists only on systems that support job control.) Puts each specified job into the background. The current job is put in the background if job is not specified. See Jobs for a description of the format of job.

† break [ n ] Exit from the enclosing for, while, until, or select loop, if any. If n is specified, then break n levels.

builtin [ -ds ] [ -f file ] [name ... ]

If name 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, each name represents the pathname whose basename is the name of the built-in. The entry point function name is determined by prepending b_ to the built-in name. A built-in specified by a pathname will only be executed when that pathname would be found during the path search. Built-ins found in libraries loaded via the .pathsfile will be associate with the pathname of the directory containing the.paths file. Special built-ins cannot be bound to a pathname or deleted. The -doption 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 available for subsequent invocations of builtin. Multiple libraries can be specified with separate invocations of the builtin 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 library whose name is lib_init() and invokes this function with an argument of 0.

cd [ -LP ] [ arg ] cd [ -LP ] old new

This command can be in either of two forms. In the first form it changes the current directory to arg. If arg is - the directory is changed to the previous directory. The shell variable HOME is the default arg. The variable PWD is set to the current directory. The shell variable CDPATHdefines the search path for the directory containing arg. Alternative directory names are separated by a 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 sign or between the colon delimiters anywhere else in the pathlist. If arg begins with a / then the search path is not used. Otherwise, each directory in the path is searched for arg. The second form of cdsubstitutes the string new for the string old in the current directory name, PWD, and tries to change to this new directory. By default,symbolic link names are treated literally when finding the directory name. This is equivalent to the -L option. The -P option causes symbolic links to be resolved when determining the directory. The last instance of -L or -P on the command line determines which method is used. The cd command may not be executed by rksh.

command [ -pvxV ]name [ arg ... ]

Without the -v or -V options, command executes name with the arguments given by arg. The -p option causes a default path to be searched rather than the one defined by the value of PATH. Functions will not be searched for when finding name. In addition, if name refers to a special built-in, none of the special properties associated with the leading daggers ("†") will be honored. (For example, the predefined alias redirect=′command exec′ prevents a script from terminating when an invalid redirection is given.) With the -x option, if command execution would result in a failure because there are too many arguments, errno E2BIG, the shell will invoke command name multiple times with a subset of the arguments on each invocation. Arguments

that occur prior to the first word that expands to multiple arguments and after the last word that 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-in whence command described below. The -V option causes command to act like whence -v.

† continue [ n ] Resume the next iteration of the enclosing for, while, until, or selectloop. If n is specified, then resume at the n-th enclosing loop.

disown [ job... ] Causes the shell not to send a HUP signal to each given job, or all active jobs if job is omitted, when a login shell terminates.

echo [ arg ... ] When the first arg does not begin with a -, and none of the arguments contain a \, then echo prints each of its arguments separated by a space and terminated by a newline. Otherwise, the behavior of echo is system dependent and print or printf described below should be used. See echo for usage and description.

†† enum [ -i ] type[=(value ...) ] Creates a declaration command named type that is an integer type that allows one of the specified values as enumeration names. If =(value...) is omitted, then type must be an indexed array variable with at least 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 input to the shell and the resulting command(s) executed.

† exec [ -c ] [ -a name ] [ arg ... ]

If arg is given, the command specified by the arguments is executed in place of this shell without creating a new process. The -c option causes the environment to be cleared before applying variable assignments associated with the exec invocation. The -a option causes name rather than the first arg, to become argv[0] for the new process. Input/output arguments may appear and affect the current process. If arg is not given, the effect of this command is to modify file descriptors as prescribed by the input/output redirection list. In this case, any

file descriptor numbers greater than 2 that are opened with this mechanism are closed when invoking another program.

† exit [ n ] Causes the shell 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. An end-of-file will also cause the shell to exit except for a shell which has the ignoreeof option (see set below) turned on.

†† export [ -p ] [name[=value] ] ...

If name is not given, the names and values of each variable with theexport attribute are printed with the values quoted in a manner that allows them to be re-input. The export command is the same astypeset -x except that if you use export within a function, no local variable is created. The -p option causes the word export to be inserted before each one. Otherwise, the given names are marked for automatic export to the environment of subsequently-executed commands.

false Does nothing, and exits 1. Used with until for infinite loops.

fg [ job... ] This command is only on systems that support job control. Each jobspecified is brought to the foreground and waited for in the specified order. Otherwise, the current job is brought into the foreground. SeeJobs for a description of the format of job.

getconf [ name [pathname ] ] Prints the current value of the configuration parameter given by name. The configuration parameters are defined by the IEEE POSIX 1003.1 and IEEE POSIX 1003.2 standards. The pathname argument is required for parameters whose value depends on the location in the file system. If no arguments are given, getconf prints the names and values of the current configuration parameters. The pathname / is used for each of the parameters that requires pathname.

getopts [ -a name ]optstring vname [ arg ... ]

Checks arg for legal options. If arg 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 when optstring begins with a +. optstring contains the letters that getopts 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-? causes getopts to generate a usage message on standard error. The-a argument can be used to specify the name to use for the usage message, which defaults to $0. getopts places the next option letter it finds inside variable vname each time it is invoked. The option letter will be prepended with a + when arg begins with a +. The index of the next arg is stored in OPTIND. The option argument, if any, gets stored in OPTARG. A leading : in optstring causes getopts to store the letter of an invalid option in OPTARG, and to set vname 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 from first to last is selected from the last HISTSIZE commands that were typed at the terminal. The arguments first and last may be specified as a number or as a string. A string is used to locate the most recent command starting with the given string. A negative number is used as an offset to the current command number. If the -l option is selected, the commands are listed on standard output. Otherwise, the editor program ename is invoked on a file containing these keyboard commands. If ename 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. If last is not specified, then it will be set to first. If first is not specified, the default is the previous command for editing and -16for listing. The option -r reverses the order of the commands and the option -n suppresses

command numbers when listing. In the second form, command is interpreted as first described above and defaults to the last command executed. The resulting command is executed after the optional substitution old=new is performed.

jobs [ -lnp ] [ job ... ] Lists information about each given job; or all active jobs if job 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 last notified. The -p option causes only the process group to be listed. See Jobs for a description of the format of job.

kill [ -s signame ] job ... kill [ -n signum ] job ... kill -Ll [ sig ... ]

Sends either the TERM (terminate) signal or the specified 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" with the exception that SIGCLD is namedCHLD). For backward compatibility, the n and s can be omitted and the number or name placed immediately after the -. If the signal being sent is TERM (terminate) or HUP (hangup), then the job or process will be sent a CONT (continue) signal if it is stopped. The argument job can be the process id of a process that is not a member of one of the active jobs. See Jobs for a description of the format of job. In the third form,kill -l, or kill -L, if sig is not specified, the signal names are listed. The -l option list only the signal names. -L options lists each signal name and corresponding number. Otherwise, for each sig that is a name, the corresponding signal number is listed. For each sig that is a number, the signal name corresponding to the least significant 8 bits of sig is listed.

let arg ... Each arg is a separate arithmetic expression to be evaluated. let only recognizes octal constants starting with 0 when the set option letoctalis on. See Arithmetic Evaluation above, for a description of arithmetic expression evaluation. The exit status is 0 if the value of the last expression is non-zero, and 1 otherwise.

† newgrp [ arg ... ] Equivalent to exec "/bin/newgrp arg ...".

print [ -CRenprsv ] [ -uunit] [ -f format ] [ arg ... ]

With no options or with option - or --, each arg is printed on standard output. The -f option causes the arguments to be printed as described by printf. In this case, any e, n, r, R options are ignored. Otherwise, unless the -C, -R, -r, or -v are specified, the following escape conventions will be applied:

\a The alert character (ASCII 07).

\b The backspace character (ASCII 010).

\c Causes print to end without processing more arguments and not adding a newline.

\f The formfeed character (ASCII 014).

\n The newline character (ASCII 012).

\r The carriage return character (ASCII 015).

\t The tab character (ASCII 011).

\v The vertical tab character (ASCII 013).

\E The escape character (ASCII 033).

\\ The backslash character \.

\0x The character defined by the 1, 2, or 3-digit octal string given by x.

The -R option will print all subsequent arguments and options other 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 the arguments to be written onto the pipe of the process spawned with ⎪& instead of standard output. The -v option treats each arg as a variable name and writes the value in the printf %B format. The -C option treats each arg as a variable name and writes the value in the printf %#B format. The -s option causes the arguments to be written onto the history file instead of standard output. The -u option can be used to specify a one digit file descriptor unit number unit on which the output will be placed. The default is 1. If the option -n is used, no newline is added to the output.

printf format [ arg ... ] The arguments arg are printed on standard output in accordance with the ANSI-C formatting rules associated with the format string format. If the number of arguments exceeds the number of format specifications, the format 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 corresponding arg to be expanded as described in print.

%B A %B option causes each of the arguments to be treated as variable names and the binary value of variable will 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 attribute is -b.

%H A %H format can be used instead of %s to cause characters in arg that are special in HTML and XML to be output as their entity name. The alternate flag # formats the output for use as a URI.

%P A %P format can be used instead of %s to cause arg to be interpreted as an extended regular expression and be printed as a shell pattern.

%R A %R format can be used instead of %s to cause arg to be interpreted as a shell pattern and 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 can be reinput to the shell. When q is preceded by the alternative format specifier, #, the string is quoted in manner

suitable as a field in a .csv format file.

%(date-format)T

A %(date-format)T format can be use to treat an argument as a date/time string and to format the date/time according to the date-format as defined for thedate 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 causes base# to be prepended.

# The # flag, when used with the %d format without an output base, displays the output in powers of 1000 indicated by one of the following suffixes: k M G T P E, and when used with the %i format displays the output in powers of 1024 indicated by one of the following suffixes:Ki Mi Gi Ti Pi Ei.

= The = flag centers the output within the specified field width.

L The L flag, when used with the %c or %s formats, treats precision as character width instead of byte count.

, The , flag, when used with the %d or %f formats, separates groups of digits with the grouping delimiter (,on groups of 3 in the C locale.)

pwd [ -LP ] Outputs the value of the current working directory. The -L option is the default; it prints the logical name of the current directory. If the -Poption is given, all symbolic links are resolved from the name. The last instance of -L or -P on the command line determines which

method is used.

read [ -ACSprsv ] [ -ddelim] [ -n n] [ [ -N n] [ [-t timeout] [ -u unit] [vname?prompt ] [ vname... ]

The shell input mechanism. One line is read and is broken up into fields using the characters in IFS as separators. The escape character, \, is used to remove any special meaning for the next character and for line continuation. The -d option causes the read to continue to the first character of delim rather than newline. The -n option causes at most nbytes to read rather a full line but will return when reading from a slow device as soon as any characters have been read. The -N option causes exactly n to be read unless an end-of-file has been encountered or the read times out because of the -t option. In raw mode, -r, the \character is not treated specially. The first field is assigned to the firstvname, the second field to the second vname, etc., with leftover fields assigned to the last vname. When vname has the binary attribute and -n or -N is specified, the bytes that are read are stored directly into the variable. If the -v is specified, then the value of the first vname will be used as a default value when reading from a terminal device. The -Aoption causes the variable vname to be unset and each field that is read to be stored in successive elements of the indexed array vname. The -C option causes the variable vname to be read as a compound variable. Blanks will be ignored when finding the beginning open parenthesis. The -S option causes the line to be treated like a record in a .csv format file so that double quotes can be used to allow the delimiter character and the newline character to appear within a field. The -p option causes the input line to be taken from the input pipe of a process spawned by the shell using ⎪&. 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 file descriptor unit unit to read from. The file descriptor can be opened with the exec special built-in command. The default value of unit n is 0. The option -t is used to specify a timeout in seconds when reading from a terminal or pipe. If vname is omitted, then REPLY is used as the default vname. An end-of-file with the -p option causes cleanup for this process so that another can be spawned. If the first argument contains a ?, the remainder of this word is used as a

prompt on standard error when the shell is interactive. The exit status is 0 unless an end-of-file is encountered or read has timed out.

†† readonly [ -p ] [vname[=value] ] ...

If vname is not given, the names and values of each variable with thereadonly attribute is printed with the values quoted in a manner that allows them to be re-inputted. The -p option causes the word readonlyto be inserted before each one. Otherwise, the given vnames are marked readonly and these names cannot be changed by subsequent assignment. When defining a type, if the value of a readonly sub-variable is not defined the value is required when creating each instance.

† return [ n ] Causes a shell function or . script to return to the invoking script 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 return status is that of the last command executed. If return is invoked while not in a function or a . script, then it behaves the same as exit.

† set [±BCGabefhkmnoprstuvx] [ ±o [ option ] ] ... [ ±Avname ] [ arg ... ]

The options for this command are as follows:

-A

Array assignment. Unset the variable vname and assign values sequentially from the arg list. If +A is used, the variable vnameis 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-directories when 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 changes state rather than waiting for the next prompt.

-e

Unless contained in a ⎪⎪ or && command, or the command following an if, while, or until 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 command becomes 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 group and 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 for interactive 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:

allexport Same as -a.

errexit Same as -e.

bgnice All background jobs are run at a lower priority. This is the default mode.

braceexpand Same as -B.

emacs Puts you in an emacs style in-line editor for command entry.

globstar Same as -G.

gmacs Puts you in a gmacs style in-line editor for command entry.

ignoreeof The shell will not exit on end-of-file. The command exit must be used.

keyword Same as -k.

letoctal The let command allows octal constants starting with 0.

markdirs All directory names resulting from file name generation have a trailing / appended.

monitor Same as -m.

multiline The built-in editors will use multiple lines on the screen for lines that are longer than the width of the screen. This may not work for all terminals.

noclobber 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 components of the pipeline have completed, and the return value will be the value of the last non-zero command to fail or zero if no command has failed.

showme When enabled, simple commands or pipelines preceded by a semicolon (;) will be displayed as if the xtrace option were enabled but will not be executed. Otherwise, the leading ; will be ignored.

privileged Same as -p.

verbose Same as -v.

trackall Same as -h.

vi Puts you in insert mode of a vi style in-line editor until you hit the escape character (ASCII code 033). This puts you in control mode. A return sends the line.

viraw Each character is processed as it is typed in vimode.

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 be set to the real uid and gid.

-r Enables the restricted shell. This option cannot be unset once 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.

† shift [ n ] The positional parameters from $n+1 ... are renamed $1 ... , default nis 1. The parameter n can be any arithmetic expression that evaluates to a non-negative number less than or equal to $#.

sleep seconds Suspends execution for the number of decimal seconds or fractions of a second given by seconds.

† trap [ -p ] [ action ] [sig ] ... The -p option causes the trap action associated with each trap as specified by the arguments to

be printed with appropriate quoting. Otherwise, action will be processed as if it were an argument to evalwhen the shell receives signal(s) sig. Each sig 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 that was ignored on entry to the current shell is ineffective. If action is omitted and the first sig is a number, or if action is -, then the trap(s) for each sig are reset to their original values. If action is the null string then this signal is ignored by the shell and by the commands it invokes. If sig is ERRthen action will be executed whenever a command has a non-zero exit status. If sig is DEBUG then action will be executed before each command. The variable .sh.command will contain the contents of the current command line when action is running. If the exit status of the trap is 2 the command will not be executed. If the exit status of the trap is 255 and inside a function or a dot script, the function or dot script will return. If sig is 0 or EXIT and the trap statement is executed inside the body of a function defined with the function name syntax, then the command action is executed after the function completes. Ifsig is 0 or EXIT for a trap set outside any function then the commandaction is executed on exit from the shell. If sig is KEYBD, then actionwill be executed whenever a key is read while in emacs, gmacs, or vimode. The trap command with no arguments prints a list of commands associated with each signal number.

An exit or return without an argument in a trap action will preserve the exit

status of the command that invoked the trap.

true Does nothing, and exits 0. Used with while for infinite loops.

†† typeset [±ACHSfblmnprtux] [ ±EFLRXZi[n] ] [ +-M [ mapname] ] [ -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 the function name syntax, a new instance of the variable vname is created, and the variable's value and type are restored when the function completes. The following list of attributes may be specified:

-A

Declares vname to be an associative array. Subscript rather than arithmetic expressions.

-C

causes each vname to be a compound variable. value nam compound variable it is copied into vname. Otherwise, it u eachvname.

-a

Declares vname to be an indexed array. If type is specifie be the name of an enumeration type created with the enum command and it allows enumeration constants as subscripts.

-E

Declares vname to be a double precision floating point nu If n is non-zero, it defines the number of significant figure used when expanding vname. Otherwise, ten significant f be used.

-F

Declares vname to be a double precision floating point nu If n is non-zero, it defines the number of places after the point that are used when expanding vname. Otherwise te after the decimal point will be used.

-H

This option provides UNIX to host-name file mapping on n machines.

-L

Left justify and remove leading blanks from value. If n is defines the width of the field, otherwise it is determined b of the value of first assignment. When the variable is assi is filled on the right with blanks or truncated, if necessary the field. The -R option is turned off.

-M

Use the character mapping mapping defined by wctrans astolower and toupper when assigning a value to each o specified operands. When mapping is specified and there operands, all variables that use this mapping are written t output. When mapping is omitted and there are no operan mapped variables are written to standard output.

-R

Right justify and fill with leading blanks. If n is non-zero, the width of the field, otherwise it is determined by the w value of first assignment. The field is left filled with blanks truncated from the end if the variable is reassigned. The - turned off.

-S

When used within the assign_list of a type definition, it c specified sub-variable to be shared by all instances of the When used inside a function defined with the function res the specified variables will have function static scope. Oth variable is unset prior to processing the assignment list.

-T

If followed by tname, it creates a type named by tname u compound assignment assign_list to tname. Otherwise, the type definitions to standard output.

-X

Declares vname to be a double precision floating point nu expands using the %a format of ISO-C99. If n is non-zer the number of hex digits after the radix point that is used expanding vname. The default is 10.

-Z

Right justify and fill with leading zeros if the first non-blan is a digit and the -L option has not been set. Remove lead the-L option is also set. If n is non-zero, it defines the wid field, otherwise it is determined by the width of the value assignment.

-f The names refer to function names rather than variable n assignments can be made and the only other valid option t, -uand -x. The -S can be used with discipline functions d type to indicate that the function is static. For a static fun same method will be used by all instances of that type no which instance references it. In addition, it can only use v variables from the original type definition. These discipline cannot be redefined in any type instance. The -t option tu execution tracing for this function. The -u option causes t to be marked undefined. The FPATH variable will be sear the function definition when the function is referenced. If other than -f is specified, then the function definition will displayed on standard output. If +f is specified, then a lin containing the function name followed by a shell commen the line number and path name of the file where this func defined, if any, is displayed. The exit status can be used t determine whether the function is defined so thattypeset .sh.math.name will return 0 when math function name i and non-zero otherwise.

-b

The variable can hold any number of bytes of data. The d text or binary. The value is represented by the base64 en the data. If -Z is also specified, the size in bytes of the da buffer will be determined by the size associated with the - the base64 string assigned results in more data, it will be Otherwise, it will be filled with bytes whose value is zero. The printf format %B can be used to output the actual d buffer instead of the base64 encoding of the data.

-h

Used within type definitions to add information when gene information about the sub-variable on the man page. It is when used outside of a type definition. When used with -f information is associated with the corresponding discipline

-i Declares vname to be represented internally as integer. T hand side of an assignment is evaluated as an arithmetic when assigning to an integer. If n is non-zero, it defines t arithmetic base, otherwise the output base will be ten.

-l Used with -i, -E or -F, to indicate long integer, or long flo Otherwise, all upper-case characters are converted to low The upper-case option, -u, is turned off. Equivalent to -M

-m

moves or renames the variable. The value is the name of whose value will be moved to vname. The original variabl unset. Cannot be used with any other options.

-n

Declares vname to be a reference to the variable whose n defined by the value of variable vname. This is usually us reference a variable inside a function whose name has be as an argument. Cannot be used with any other options.

-p

The name, attributes and values for the given vnames are standard output in a form that can be used as shell input. specified, then the values are not displayed.

-r The given vnames are marked readonly and these names changed by subsequent assignment.

-t Tags the variables. Tags are user definable and have no s meaning to the shell.

-u

When given along with -i, specifies unsigned integer. Oth lower-case characters are converted to upper-case. The lo option, -l, is turned off. Equivalent to -M toupper.

-x

The given vnames are marked for automatic export to the environment of subsequently-executed commands. Variab 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 no vnamearguments are given, a list of vnames (and optionally the values) of the variables is printed. (Using + rather than - keeps the values from being printed.) The -p option causes typeset followed by the option letters to be printed before each name rather than the names of the options. If any option other than -p is given, only those variables which have all of the given options are printed. Otherwise, the vnames and attributes of all variables that have attributes are 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 when limit is specified. The value of limit can be a number in the unit specified below with each resource,

or the value unlimited. The -H and -S options specify whether the hard limit or the soft limit for the given resource is set. A hard limit cannot be increased once it is set. A soft limit can be increased up to the value of the hard limit. If neither the H nor Soption is specified, the limit applies to both. The current resource limit is printed when limit is omitted. In this case, the soft limit is printed unless H is specified. When more than one resource is specified, then the limit name 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 du

-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 w current process or by child processes (files of any siz

-m

The number of K-bytes on the size of physical memo

-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 proc

-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 to mask (see umask). mask can either be an octal number or a symbolic value as described in the documentation of chmod. If a symbolic value is given, the new umask value is the complement of the result of applying mask 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 symbolic value. Otherwise, the

mask is printed in octal.

† unalias [ -a ]name ... The aliases given by the list of names are removed from the alias list. The -aoption causes all the aliases to be unset.

† unset [ -fnv ]vname ... The variables given by the list of vnames 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 the default value from the type definition. Readonly variables cannot be unset. If the -f option is set, then the names refer to function names. If the -v option is set, then the names refer to variable names. The -f option overrides -v. If -n is set and name is a name reference, then name will be unset rather than the variable that it references. The default is equivalent to -v. Unsetting LINENO, MAILCHECK, OPTARG,OPTIND, RANDOM, SECONDS, TMOUT, and _ removes their special meaning even if they are subsequently assigned to.

wait [ job ... ] Wait for the specified job and report its termination status. If job is not given, then all currently active child processes are waited for. The exit status from this command is that of the last process waited for if job is specified; otherwise it is zero. See Jobs for a description of the format of job.

whence [ -afpv ]name ...

For each name, indicate how it would be interpreted if used as a command name. The -v option produces a more verbose report. The -f option skips the search for functions. The -p option does a path search for name even if name is an alias, a function, or a reserved word. The -p option turns off the -voption. The -a option is similar to the -v option but causes all interpretations of the given name to be reported.

Invocation

If the shell is invoked by exec, and the first character of argument zero ($0) is -, then the shell is assumed to be a login shell and commands 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 from the file named by performing parameter expansion, command

substitution, and arithmetic substitution on the value of the environment

variable ENV if the file exists. If the -s option is not present and arg and a file by

the name of arg exists, then it reads and executes this script. Otherwise, if the

first arg does not contain a /, a path search is performed on the first arg to

determine the name of the script to execute. The script arg must have execute

permission and any setuid and setgid 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 shell when it is invoked:

-D Do not execute the script, but output the set of double quoted strings preceded by a $. These strings are needed for localization of the script to different locales.

-E Reads the file named by the ENV variable or by $HOME/.kshrc if not defined after the profiles.

-c If the -c option is present, then commands are read from the first arg. Any remaining arguments become positional parameters starting at 0.

-s If the -s option is present or if no arguments remain, then commands are read from the standard input. Shell output is written to file descriptor 2.

-i If the -i option is present or if the shell input and output are attached to a terminal (as told by tcgetattr), then this shell is interactive. In this case TERM is ignored (so that kill 0 does not kill an interactive shell) and INTR is caught and ignored. In all cases, QUITis 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 translation when 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.

-Rfilename

The -R filename option is used to generate a cross reference database that can be used by a separate utility to find definitions and references for variables and commands.

The remaining options and arguments are described under the set command

above. An optional - as the first argument is ignored.

Rksh Only

Rksh is used to set up login names and execution environments whose

capabilities are more controlled than those of the standard shell. The actions

of rksh are identical to those of ksh, except that the following are disallowed: • Unsetting the restricted option • changing directory (see cd)

• setting or unsetting the value or attributes of SHELL, ENV, FPATH, or PATH • specifying path or command names containing / • redirecting output (>, >|, <>, and >>) • adding or deleting built-in commands • using command -p to invoke a command

The restrictions above are enforced after .profile and the ENV files are

interpreted.

When a command to be executed is found to be a shell

procedure, rksh invokes ksh to execute it. Thus, it is possible to provide to the

end-user shell procedures that have access to the full power of the standard

shell, while imposing a limited menu of commands; this scheme assumes that

the end-user does not have write and execute 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 actions and leaving

the user in an appropriate directory (probably not the login directory).

The system administrator often sets up a directory of commands

(e.g., /usr/rbin) that can be safely invoked by rksh.

Exit Status

Errors detected by the shell, such as syntax errors, cause the shell to return a

non-zero exit status. If the shell is being used non-interactively, then execution

of the shell file is abandoned unless the error occurs inside a subshell in which

case the subshell is abandoned. Otherwise, the shell returns the exit status of

the last command executed (see also the exit command above). Runtime errors

detected by the shell are reported by printing 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.

Files

/etc/profile The system wide initialization file, executed for login shells.

$HOME/.profile The personal initialization file, executed for login shells after /etc/profile.

$HOME/..kshrc Default personal initialization file, executed for interactive shells when ENV is not set.

/etc/suid_profile Alternative initialization file, executed instead of the personal initialization file when the real and effective user or group id do not match.

/dev/null The null device.

Examples

ksh

Invokes the Korn shell.

Related commands

bash csh sh