[ Previous | Next | Table of Contents | Index | Library Home | Legal | Search ]

System User's Guide: Operating System and Devices


C Shell Commands

A simple command is a sequence of words separated by blanks or tabs.

A word is a sequence of characters or numerals, or both, that does not contain blanks without quotation marks. In addition, the following characters and doubled characters also form single words when used as command separators or terminators:

&       |      ;        
&&      ||    <<        > >
<       >     (          )

These special characters can be parts of other words. Preceding them with a \, however, prevents the shell from interpreting them as special characters. Strings enclosed in ' ' or " " (matched pairs of quotation characters) or backquotes can also form parts of words. Blanks, tab characters, and special characters do not form separate words when they are enclosed in these marks. In addition, you can enclose a new-line character within these marks by preceding it with a \.

The first word in the simple command sequence (numbered 0) usually specifies the name of a command. Any remaining words, with a few exceptions, are passed to that command. If the command specifies an executable file that is a compiled program, the shell immediately runs that program. If the file is marked executable but is not a compiled program, the shell assumes that it is a shell script. In this case, the shell starts another instance of itself (a subshell) to read the file and execute the commands included in it.

This section discusses:

C Shell Built-In Commands

Built-in commands are run within the shell. If a built-in command occurs as any component of a pipeline, except the last, the command runs in a subshell.

Note: If you enter a command from the C shell prompt, the system searches for a built-in command first. If a built-in command does not exist, the system searches the directories specified by the path shell variable for a system-level command. Some C shell built-in commands and operating system commands have the same name. However, these commands do not necessarily work the same way. Check the appropriate command description for information on how the command works.

If you run a shell script from the shell and the first line of the shell script begins with #!/ShellPathname, the C shell runs the shell specified in the comment to process the script. Otherwise, it runs the default shell (the shell linked to /usr/bin/sh). If run by the default shell, C shell built-in commands might not be recognized. To get the system to run C shell commands, make the first line of the script #!/usr/bin/csh.

Refer to the List of C Shell Built-in Commands for an alphabetic listing of the built-in commands.

C Shell Command Descriptions

The C shell provides the following built-in commands:

alias [Name [WordList]] Displays all aliases if you do not specify any parameters. Otherwise, the command displays the alias for the specified Name. If WordList is specified, this command assigns the value of WordList to the alias Name. The specified alias Name cannot be alias or unalias.
bg [%Job ...] Puts the current job or job specified by Job into the background, continuing the job if it was stopped.
break Resumes running after the end of the nearest enclosing foreach or while command.
breaksw Breaks from a switch command; resumes after the endsw command.
case Label: Defines a Label in a switch command.
cd[Name] Equivalent to the chdir command (see following description).
chdir [Name] Changes the current directory to that specified by the Name variable. If you do not specify Name, the command changes to your home directory. If the value of the Name variable is not a subdirectory of the current directory and does not begin with /, ./, or ../, the shell checks each component of the cdpath shell variable to see if it has a subdirectory matching the Name variable. If the Name variable is a shell variable with a value that begins with /, the shell tries this to see if it is a directory. The chdir command is equivalent to the cd command.
continue Continues execution at the end of the nearest enclosing while or foreach command.
default: Labels the default case in a switch statement. The default should come after all other case labels.
dirs Displays the directory stack.
echo Writes character strings to the standard output of the shell.
else Runs the commands that follow the second else in an if (Expression) then ...else if (Expression2) then ... else ... endif command sequence.
end Successively sets the Name variable to each member specified by the List variable and runs the sequence of Commands between the foreach and the matching end statements. The foreach and end statements must appear alone on separate lines.

Uses the continue statement to continue the loop and the break statement to end the loop prematurely. When the foreach command is read from the terminal, the C shell prompts with a ? to allow Commands to be entered. Commands within loops, prompted for by ?, are not placed in the history list.

endif If the Expression variable is true, runs the Commands that follow the first then statement. If the else if Expression2 is true, runs the Commands that follow the second then statement. If the else if Expression2 is false, runs the Commands that follow the else. Any number of else if pairs are possible. Only one endif statement is needed. The else segment is optional. The words else and endif can be used only at the beginning of input lines. The if segment must appear alone on its input line or after an else command.
endsw Successively matches each case label against the value of the string variable. The string is command and file name expanded first. Use the pattern-matching characters *, ?, and [ . . . ] in the case labels, which are variable-expanded. If none of the labels match before a default label is found, the execution begins after the default label. The case label and the default label must appear at the beginning of the line. The breaksw command causes execution to continue after the endsw command. Otherwise, control might fall through the case and default labels, as in the C programming language. If no label matches and there is no default, execution continues after the endsw command.
eval Parameter . . .  Reads the value of the Parameter variable as input to the shell and runs the resulting command or commands in the context of the current shell. Use this command to run commands generated as the result of command or variable substitution, since parsing occurs before these substitutions.
exec Command Runs the specified Command in place of the current shell.
exit [(Expression) Exits the shell with either the value of the status shell variable (if no Expression is specified) or with the value of the specified Expression.
fg [%Job ...] Brings the current job or job specified by Job into the foreground, continuing the job if it was stopped.
foreach Name (List) Command. . .   Successively sets a Name variable for each member specified by the List variable and a sequence of commands, until reaching an end command.
glob List Displays List using history, variable, and file name expansion. Puts a null character between words and does not include a carriage return at the end.
goto Word Continues to run after the line specified by the Word variable. The specified Word is file name and command expanded to yield a string of the form specified by the Label: variable. The shell rewinds its input as much as possible and searches for a line of the form Label:, possibly preceded by blanks or tabs.
hashstat Displays statistics indicating how successful the hash table has been at locating commands.
history [-r | -h] [n] Displays the history event list. The oldest events are displayed first. If you specify a number n, only the specified number of the most recent events are displayed. The -r flag reverses the order in which the events are displayed so the most recent is displayed first. The -h flag displays the history list without leading numbers. Use this flag to produce files suitable for use with the -h flag of the source command.
if (Expression) Command Runs the specified Command (including its arguments) if the specified Expression is true. Variable substitution on the Command variable happens early, at the same time as the rest of the if statement. The specified Command must be a simple command (rather than a pipeline, command list, or parenthesized command list).

Note: Input and output redirection occurs even if the Expression variable is false and the Command is not executed.
jobs [-l] Lists the active jobs. With the -l (lowercase L) flag, the jobs command lists process IDs in addition to the job number and name.
kill -l | [[-Signal] % Job...|PID...] Sends either the TERM (terminate) signal or the signal specified by Signal to the specified Job or PID (process). Specify signals either by number or by name (as given in the /usr/include/sys/signal.h file, stripped of the SIG prefix). The -l (lowercase L) flag lists the signal names.
limit [-h] [Resource [Max-Use]] Limits the usage of the specified resource by the current process and each process it creates. Process resource limits are defined in the /etc/security/limits file. Controllable resources are the central processing unit (CPU) time, file size, data size, core dump size, and memory use. Maximum allowable values for these resources are set with the mkuser command when the user is added to the system. They are changed with the chuser command.

Limits are categorized as either soft or hard. Users may increase their soft limits up to the ceiling imposed by the hard limits. You must have root user authority to increase a soft limit above the hard limit, or to change hard limits. The -h flag displays hard limits instead of the soft limits.

If a Max-Use parameter is not specified, the limit command displays the current limit of the specified resource. If the Resource parameter is not specified, the limit command displays the current limits of all resources. For more information about the resources controlled by the limit subcommand, see the getrlimit, setrlimit, or vlimit subroutine in the AIX 5L Version 5.1 Technical Reference: Base Operating System and Extensions Volume 1.

The Max-Use parameter for CPU time is specified in the hh:mm:ss format. The Max-Use parameter for other resources is specified as a floating-point number or an integer optionally followed by a scale factor. The scale factor is: k or kilobytes (1024 bytes), m or megabytes, or b or blocks (the units used by the ulimit subroutine as explained in the AIX 5L Version 5.1 Technical Reference: Base Operating System and Extensions Volume 2 ). If you do not specify a scale factor, k is assumed for all resources. For both resource names and scale factors, unambiguous prefixes of the names suffice.

Note: This command limits the physical memory (memory use) available for a process only if there is contention for system memory by other active processes.
login Ends a login shell and replaces it with an instance of the /usr/bin/login command. This is one way to log out (included for compatibility with the ksh and bsh commands).
logout Ends a login shell. This command must be used if the ignoreeof option is set.
nice [+n] [Command] If no values are specified, sets the priority of commands run in this shell to 24. If the +n flag is specified, sets the priority plus the specified number. If the +n flag and Command are specified, runs Command at priority 24 plus the specified number. If you have root user authority, you can run the nice statement with a negative number. The Command always runs in a subshell, and the restrictions placed on commands in simple if statements apply.
nohup [Command] Causes hangups to be ignored for the remainder of the script when no Command is specified. If Command is specified, causes the specified Command to be run with hangups ignored. To run a pipeline or list of commands, put the pipeline or list in a shell script, give the script execute permission, and use the shell script as the value of the Command variable. All processes run in the background with & are effectively protected from being sent a hangup signal when you log out. However, these processes are still subject to explicitly sent hangups unless the nohup statement is used.
notify [%Job...] Causes the shell to notify you asynchronously when the status of the current job or specified Job changes. Normally, the shell provides notification just before it presents the shell prompt. This feature is automatic if the notify shell variable is set.
onintr [- | Label] Controls the action of the shell on interrupts. If no arguments are specified, restores the default action of the shell on interrupts, which ends shell scripts or returns to the command input level. If a - flag is specified, causes all interrupts to be ignored. If Label is specified, causes the shell to run a goto Label statement when the shell receives an interrupt or when a child process ends due to an interruption. In any case, if the shell is running detached and interrupts are being ignored, all forms of the onintr statement have no meaning. Interrupts continue to be ignored by the shell and all invoked commands.
popd [+n] Pops the directory stack and changes to the new top directory. If you specify a +n variable, the command discards the nth entry in the stack. The elements of the directory stack are numbered from the top, starting at 0.
pushd [+n|Name] With no arguments, exchanges the top two elements of the directory stack. With the Name variable, the command changes to the new directory and pushes the old current directory (as given in the cwd shell variable) onto the directory stack. If you specify a +n variable, the command rotates the nth component 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 recomputation of the internal hash table of the contents of the directories in the path shell variable. This action is needed if new commands are added to directories in the path shell variable while you are logged in. The rehash command is necessary only if commands are added to one of the user's own directories or if someone changes the contents of one of the system directories.
repeat Count Command Runs the specified Command, subject to the same restrictions as commands in simple if statements, the number of times specified by Count.

Note: I/O redirections occur exactly once, even if the Count variable equals 0.
set [[Name[n]] [ = Word]] | [Name = (List)] Shows the value of all shell variables when used with no arguments. Variables that have more than a single word as their value are displayed as a parenthesized word list. If only Name is specified, the C shell sets the Name variable to the null string. Otherwise, sets Name to the value of the Word variable, or sets the Name variable to the list of words specified by the List variable. When n is specified, the nth component of the Name variable is set to the value of the Word variable; the nth component must already exist. In all cases, the value is command and file name expanded. These arguments may be repeated to set multiple values in a single set command. However, variable expansion happens for all arguments before any setting occurs.
setenvName Value Sets the value of the environment variable specified by the Name variable to Value, a single string. The most commonly used environment variables, USER, TERM, HOME, and PATH, are automatically imported to and exported from the C shell variables user, term, home, and path. There is no need to use the setenv statement for these.
shift [Variable] Shifts the members of the argv shell variable or the specified Variable to the left. An error occurs if the argv shell variable or specified Variable is not set or has less than one word as its value.
source[-h] Name Reads commands specified by the Name variable. You can nest the source commands. However, if they are nested too deeply, the shell might run out of file descriptors. An error in a source command at any level ends all nested source commands. Normally, input during source commands is not placed on the history list. The -h flag causes the commands to be placed in the history list without executing them.
stop [%Job ...] Stops the current job or specified Job running in the background.
suspend Stops the shell as if a STOP signal had been received.
switch (string) Starts a switch (String) case String : ... breaksw default: ... breaksw endsw command sequence. This command sequence successively matches each case label against the value of the String variable. If none of the labels match before a default label is found, the execution begins after the default label.
time [Command] The time command controls automatic timing of commands. If you do not specify the Command variable, the time command displays a summary of time used by this shell and its children. If you specify a command with the Command variable, it is timed. The shell then displays a time summary, as described under the time shell variable. If necessary, an extra shell is created to display the time statistic when the command completes.

Here is an example using time with the sleep command:

time sleep

The output from this command might look like:

0.0u 0.0s 0:00 100% 44+4k 0+0io 0pf+0w

The seven fields in the output are described below:

Field
Description

First
Number of seconds of CPU time devoted to the user process

Second
Number of seconds of CPU time consumed by the kernel on behalf of the user process

Third
Elapsed (wall clock) time for the command

Fourth
Total user CPU Time plus system time, as a percentage of elapsed time

Fifth
Average amount of shared memory used, plus average amount of unshared data space used, in kilobytes

Sixth
Number of block input and output operations

Seventh
Page faults plus number of swaps
umask [Value] Determines file permissions. This Value, along with the permissions of the creating process, determines a file's permissions when the file is created. The default is 022. The current setting will be displayed if no Value is specified.
unalias *|Pattern Discards all aliases with names that match the Pattern variable. All aliases are removed by the unalias * command. The absence of aliases does not cause an error.
unhash Disables the use of the internal hash table to locate running programs.
unlimit [-h][Resource] Removes the limitation on the Resource variable. If no Resource variable is specified, all resource limitations are removed. See the description of the limit command for the list of Resource names.

The -h flag removes corresponding hard limits. Only a user with root user authority can change hard limits.

unset *|Pattern Removes all variables with names that match the Pattern variable. Use unset * to remove all variables. If no variables are set, it does not cause an error.
unsetenv Pattern Removes all variables from the environment whose name matches the specified Pattern. (See the setenv built-in command.)
wait Waits for all background jobs. If the shell is interactive, an INTERRUPT (usually the Ctrl-C key sequence) disrupts the wait. The shell then displays the names and job numbers of all jobs known to be outstanding.
while (Expression) Command. . .  end Evaluates the Commands between the while and the matching end statements while the expression specified by the Expression variable evaluates nonzero. You can use the break statement to end and the continue statement to continue the loop prematurely. The while and end statements must appear alone on their input lines. If the input is from a terminal, prompts occur after the while (Expression) similar to the foreach statement.
@ [Name[n] = Expression] Displays the values of all the shell variables when used with no arguments. Otherwise, sets the name specified by the Name variable to the value of the Expression variable. If the expression contains <, >, &, or | characters, this part of the expression must be placed within parentheses. When n is specified, the nth component of the Name variable is set to the Expression variable. Both the Name variable and its nth component must already exist.

C language operators, such as *= and +=, are available. The space separating the Name variable from the assignment operator is optional. Spaces are, however, required in separating components of the Expression variable, which would otherwise be read as a single word. Special suffix operators, double plus sign (++) and double hyphen (- -) increase and decrease, respectively, the value of the Name variable.

C Shell Expressions and Operators

The @ built-in command and the exit, if, and while statements accept expressions that include operators similar to those of C language, with the same precedence. The following operators are available:

Operator What it Means
() change precedence
~ complement
! negation
*/ % multiply, divide, modulo
+ - add, subtract
<< > > left shift, right shift
<= >= < > relational operators
== != =~ !~ string comparison/pattern matching
& bitwise "and"
^ bitwise "exclusive or"
| bitwise "inclusive or"
&& logical "and"
|| logical "or"

In the above list, precedence of the operators decreases down the list - left to right, top to bottom.

Note: The operators + and - are right associative. For example, evaluation of a + b - c is performed as follows:

a + (b - c)

and not:

(a + b) - c

The ==, !=, =~, and !~ operators compare their arguments as strings; all others operate on numbers. The =~ and !~ operators are similar to == and != , except that the rightmost side is a pattern against which the leftmost operand is matched. This reduces the need for use of the switch statement in shell procedures when all that is really needed is pattern matching.

The logical operators or (||) and and (&&) are available as well. They can be used, for example, to check for a range of numbers:

if ($#argv > 2 && $#argv < 7) then

In the preceding example, the number of arguments must be greater than 2 and less than 7.

Strings beginning with zero (0) are considered octal numbers. Null or missing arguments are considered 0. All expressions result in strings representing decimal numbers. Note that two components of an expression can appear in the same word. Except when next to components of expressions that are syntactically significant to the parser (& | < > ( )), expression components should be surrounded by spaces.

Also available in expressions as primitive operands are command executions enclosed in ( ) and file inquiries of the form (-operator Filename), where operator is one of the following:

r Read access
w Write access
x Execute access
e Existence
o Ownership
z Zero size
f Plain file
d Directory

The specified Filename is command and file name expanded and then tested to see if it has the specified relationship to the real user. If Filename does not exist or is inaccessible, then all inquiries return false(0). If the command runs successfully, the inquiry returns a value of true(1). Otherwise, if the command fails, the inquiry returns a value of false(0). If more detailed status information is required, run the command outside an expression and then examine the status shell variable.

Command Substitution in the C Shell

In command substitution, the shell executes a specified command and replaces that command with its output. To perform command substitution in the C shell, enclose the command or command string in backquotes (` `). The shell normally breaks the output from the command into separate words at blanks, tabs, and new-line characters. It then replaces the original command with this output.

In the following example, the backquotes (` `) around the date command indicate that the output of the command will be substituted:

echo The current date and time is: `date`

The output from this command might look like:

The current date and time is: Wed Apr 8 13:52:14 CDT 1992

The C shell performs command substitution selectively on the arguments of built-in shell commands. This means that it does not expand those parts of expressions that are not evaluated. For commands that are not built-in, the shell substitutes the command name separately from the argument list. The substitution occurs in a child of the main shell, only after the shell performs input or output redirection.

If a command string is surrounded by " ", the shell treats only new-line characters as word separators, thus preserving blanks and tabs within the word. In all cases, the single final new-line character does not force a new word.

Nonbuilt-in C Shell Command Execution

When the C shell determines that a command is not a built-in shell command, it attempts to run the command with the execv system call. Each word in the path shell variable names a directory from which the shell attempts to run the command. If given neither the -c nor -t flag, the shell hashes the names in these directories into an internal table. The shell tries to call the exec system call on a directory only if there is a possibility that the command resides there. If you turn off this mechanism with the unhash command or give the shell the -c or -t flag, the shell concatenates with the given command name to form a path name of a file. The shell also does this in any case for each directory component of the path variable that does not begin with a /. The shell then attempts to run the command.

Parenthesized commands always run in a subshell. For example:

(cd ; pwd) ; pwd

displays the home directory without changing the current directory location. However, the command:

cd ; pwd 

changes the current directory location to the home directory. Parenthesized commands are most often used to prevent the chdir command from affecting the current shell.

If the file has execute permission, but is not an executable binary to the system, then the shell assumes it is a file containing shell commands and runs a new shell to read it.

If there is an alias for the shell, then the words of the alias are prefixed to the argument list to form the shell command. The first word of the alias should be the full path name of the shell.


[ Previous | Next | Table of Contents | Index | Library Home | Legal | Search ]