C SHELL

The following topics are discussed in this section:

GENERAL INFORMATION

The C shell is an interactive command interpreter and command programming language. The shell carries out commands specified at the terminal or from a file. The C shell uses a syntax that is very similar to that of the C programming language.

GETTING STARTED

The C shell is executed by the login command if it is your default shell, or by issuing the csh command. When executed, the shell runs commands found in the /etc/profile file and then in your $HOME/.login file (which may call the $HOME/.cshrc file). You can reload the C shell by issuing the command source ~/.cshrc.

USING THE C SHELL

Executing Commands

When a command is issued in the C shell, the command is evaluated and all substitutions (variables and aliases) are made. If the evaluated command matches a cshrc special command or a defined function, it is executed. If the command matches A NAME of an executable (binary) file, the shell (the parent) spawns a new (child) process which runs the binary program. If the command matches the name of a text file marked executable, the shell assumes that it is a shell procedure. To execute this procedure, the shell spawns a subshell that executes the commands specified in the file.

By default, the shell will search for external commands based on the value of the path environment variable. If the command can not be found in any of the directories specified by the path, it searches the current directory. If you specify a path with the command, the shell will not search the path for the specified command. Instead, it only searches the path specified on the command line.

Expressions

The C shell expressions are used with the @, exit, if, and while statements. C shell expressions have the same precedence as the C language and uses most of the same operators. The operators available are: *, /, %, +, -, < < , > > , < =, > =, > , < , ==, !=, =\~, and !\~. All operators work on numbers except the last four. The last two commands match the string specified to the left operand with the pattern specified to the right of the operator. The || and & & operators can also be used for logical or and logical and operations.

A command execution is a primitive operand in an expression and is placed between braces. These expressions can be used to test files attributes and compare strings. These commands return a value of 1 for true and a value of zero if the expression evaluates to false. The table below contains the commands allowed in these expressions.

Expr     Brief Description                 Expr     Brief Description
-------------------------------------------------------------------------------
-d file  T if file exists & a directory    -e file  T if file exists
-f file  T if file exists & a normal file  -o file  T if file exists & user is owner
-r file  T if file has read access         -w file  T if file exists & writable
-x file  T if file exists & executable     -z file  T if file is 0 bytes long

Special Commands

The following table shows a listing of the special commands built into the C shell. Next to each command will be a brief description of the command.

Command                 Description
-------------------------------------------------------------------------------
alias [name[=value]]    Specify a nickname for the command, value
alloc                   Shows the amount of dynamic memory acquired
bg [job...]             Place the specified job into the background
break [n]               Exits the nth iteration from the for, while, or until loop.
breaksw                 Breaks from a switch statement
case label:             Defines a label in a switch command
cd [directory]          Changes to the specified directory, or to $HOME if none specified
chdir [name]            Changes the current directory to name
continue [n]            Resumes the nth iteration of the for, while, or until loop
default:                Labels the default case in a switch statement
dirs                    Displays the directory stack
echo [string]           Writes string to standard output
else                    Used with the if statement
end                     Used with the foreach statement
endif                   Used with the if statement
endsw                   Used with the switch statement
eval [list]             Executes the commands specified in list
exec [list]             Executes the commands in list in place of the current shell
exit [n]                Causes the shell to exit with a return code of n
fg [job...]             Places the job in the foreground
foreach name(list)      Sets the name variable to each value in list and runs the commands before the end
glob list               Functions like the echo statement, but does not recognize \ escapes
goto word               Continues to run after the line specified by word
history [n]             Displays the last n commands in the history
if (expr) command       If the expr evaluates to true, the condition is executed -- works like the C function
jobs [job]              Displays all the active jobs or the specified job
kill job                Terminates the execution of the specified job
limit [resource]        Limits the usage of the specified resource
login                   Ends a login shell and replaces it with an instance of /usr/sbin/login
logout                  Ends a login shell
newgrp [group]          Executes the /usr/bin/newgrp command in the current shell process
nice +n command         Sets the priority of command to n
nohup command           Causes hang-ups to be ignored for the command
notify %job             Causes the shell to notify you when the specified job changes status
onintr label            Controls the action of the shell on interrupts
popd [+n]               Pops the nth entry from the directory stack
pushd name              Pushes name on the directory stack
rehash                  Causes the internal hash table of contents of path directories to be recalculated
repeat count cmnd       Runs cmnd count times
set variable[=value]    Sets the specified shell variable to value
shift [n]               Shifts the command line arguments to the left n places ($0 is never shifted)
source name             Reads commands specified by the file name
stop %job               Stops the specified job
suspend                 Stops the shell as if a STOP signal had been received
switch(str)             Works the same as a switch in the C language except breaksw is used instead of break
time command            Displays the accumulated user and system times for command
trap [command] [n]      Runs command when the shell receives a signal n
umask [nnn]             Sets the access mode mask to be used with newly created files.
unalias name            Removes the alias for the nickname name
unhash                  Disables the use of the internal hash table to locate running programs
unlimit [resource]      Removes the limitation on resource
unset [name...]         Removes the specified variable, name from the environment
unsetenv pattern        Removes all variables with names that match pattern
wait                    Waits for all background jobs
while (expression)      Evaluates the commands before end while expression evaluates to true

Job Control

The C shell lets you run processes in the background, freeing your terminal for the execution of more commands. You can also control processes running in the foreground as well as the background. The easiest of these functions is the [CTRL] [Z] key sequence. This will stop the current process and return you to the OS prompt. Any job can be placed in the background by issuing the bg command. The fg command should be issued when you wish to place a job in the foreground. Both of these commands take a job number as an argument. The job number is returned by the jobs command. The job number is also displayed in brackets when you place it in the background.

A command can be told to execute in the background if an ampersand (& ) is placed at the end of the command line. When the shell sees the ampersand, it will display the job number for that process in square brackets followed by its process ID. If the background process tries to read from the terminal, it will be stopped. These jobs will also stop when trying to write output if the stty tostop command has been given to the shell.

When using any of the commands to control a job (bg, fg, and kill), an argument must be passed specifying which job is to be affected. This argument represents a specific job and can be specified by the job ID preceded by a percent sign. As an alternative, you can specify the command string after the percent sign to specify a job. If you wish to specify a series of jobs that match a specific string, precede the string with the %? characters. If no arguments are given, the commands will assume you wish to choose the previously affected job.

Before logging out, you should know the statuses of any jobs which still exist. If you have stopped jobs, the shell will not allow you to logout. Before you can logout, you must resume or kill the job. If you have a job running in the background, you will be allowed to logout and the process will continue running. This, however, is strongly discouraged because it ties up valuable system resources.

Command Substitution

You can take the output of one command and use it as an argument for another command within the C shell. To do this, place the command to be used as an argument within grave accents. This will tell the shell to do a command substitution of that command for an argument in another command. The shell will then replace the command within the grave accents with the output of the command. This is particularly useful for assignments such as today = `date`.

File Name Substitution

The C shell provides a sophisticated file name substitution ability. To match any string, including the null string, use the asterisk (*). The question mark can be used to match a single character. Characters enclosed within square brackets can signify a set of characters to match. Placing an exclamation point after the open bracket will signify a pattern that matches none of the characters specified with the brackets. A hyphen between letters that are located in brackets signifies a pattern to match all characters included in the specified range.

There is an exception to the filename substitution rules. Any file that begins with a period will not match a pattern. In other words, to see a list of all files that begin with a period, you would have to use the pattern .* . If the pattern does not match any file names, the pattern is returned. Infinite recursion can occur if files have names that include any of the special pattern characters.

Redirecting Input and Output

The C shell allows you to redirect standard input, standard output, or standard error to another file or command. These devices are given file descriptors zero through two respectively. File descriptors three through nine are free to use by your applications and can also be redirected as needed. File name substitution or pattern matching does not take place after a redirection symbol. Therefore, care should be taken to ensure files are not created using any of the special pattern characters.

Redirection symbols should be used after the command and any of its arguments. The redirection symbol should then be followed by the file or command for which the redirection is occurring. The < symbol is used to redirect standard input from the specified file. The > sign redirects standard output to the specified file. The > > symbol appends the output of the command to file specified, creating it if it does not exist. You can redirect a specific file descriptor by placing its number directly after the redirection symbol and an ampersand. For example, cc prog1 > > & 2 error.file will redirect all errors produced by the c compiler to the file error.file. You can redirect more than one file descriptor by placing each one with its own redirection symbol.

Aliases

Aliases can be used to give a nickname to a command or to give A NAME to a command with a specific set of options. You can alias a command by issuing an alias command in your .profile script. The syntax for the alias command is

     alias nickname command [options]
where nickname is the nickname to be used and command is the AIX command with the specified options being aliased. When the shell finds a command being executed that matches a nickname in the alias list, it will replace the nickname on the command line with command options. This substitution is followed by a space character so the substituted string does not combine with the remainder of the command line.

Tilde (~) Substitution

The C shell uses the tilde character to represent the login area of users. This provides a quick and easy way to change to a user's login directory. When the shell finds a tilde in a command, in checks the next word. If the word following the tilde matches a userid found in the /etc/passwd file, the tilde and userid is replaced with user's login directory. If the word can not be found, the command is left unchanged. In all other cases, the shell replaces the tilde with your login directory as specified by the $HOME environment variable.

Command History

The history command will display the last set of commands issued from your terminal. To reissue one of these commands, issue the history character followed by the history number, relative history number, keyword pattern, or the keyword for the command. By default, the history character will be the exclamation mark (!). In order to use the history facilities of C shell, you must specify a value for the history environment variable. The value specified sets the number of commands history records. As a shortcut, you can issue the history character twice to repeat the last command issued to AIX.

History substitutions can also be used to edit old commands and build new commands as well as repeat them. To build a new command, simply enter the history command to repeat in the proper operand of the new command. To edit an old command, you will need to use one of the special word identifiers in the command. Most word identifiers must be preceded with a colon. The few exceptions are the '\^', '$', '*', '-', and '%'. Below is a table showing the various word identifiers and their definitions.

opt description                          opt  description
--------------------------------------------------------------------------------
0   first word (the command name)        \^   first parameter
n   nth parameter                        $    last parameter
%   word matched by a preceding search   x-y  xth parameter to yth parameter
-y  command name to yth parameter        *    all parameters
x*  xth through last parameters          x-   xth through next to last parameters
Examples:

!4

will reissue command number 4 in the history list

!?77?

will repeat the command whose second and third characters are sevens

!! > prog1.out

will repeat the last command and redirect its output to prog1.out

more !3:1

will issue the more command with history command number three's first parameter

Environment Variables

When you run a command, the shell automatically assigns the command to $0. The first argument is assigned to $1 and so on for each argument on the command line up to $9. To access any arguments past position nine, you will need to use the shift command.

The C shell lets you create and assign values to system environment variables as well as user defined variables. A variable name is a sequence of letters and numbers and can include underscores. The only restriction is that it not begin with a number. A value can be assigned to a variable by typing the variable name followed by an equals sign and then the value to be assigned. Do not place any spaces around the equals sign, or they will be included as part of the variable name or value. If you wish to use spaces in the value, place the entire value within quotation marks. If double quotation marks are used, the shell will still perform variable name substitution. In other words, values are substituted for their variables. Once a value has been assigned to a variable, it can be used by placing a $ before the variable name. If the value is to be used within a string, you can include the variable name (but not the $) within braces. The braces will separate the variable name from the rest of the string.

Below is a table showing the system environment variables and a brief description about them.

Variable   Brief Description
-----------------------------------------------------------------------------
argv[#]    The arguments passed to the shell where # is the specific argument
cdpath     The search path for the cd command
cwd        The full path name of the current working directory
echo       Set with the -x flag to the shell -- causes each command to be echoed before execution
histchars  Defines the characters used in history substitutions
history    Determines the number of commands to be stored in the history list
home       The subdirectory that becomes current upon login and as a default for cd
ignoreeof  The shell ignores the end of file character at the OS prompt
mail       The path name of the file used by the mail system to detect the arrival of new mail
noclobber  Prevents redirection from overwriting existing files
noglob     Inhibits file name expansion
nonomatch  No error reported if a file name expansion does not match any existing files
notify     If set, the shell will notifies you when the status of a job changes
path       The search path for commands separated by colons
prompt     The string displayed as the prompt by the operating system
savehist   The number of entries saved in the history list
shell      The path name of the shell (should be exported by the $HOME/.profile script
status     The status returned by the last command
time       Controls the automatic timing of commands
verbose    If set, displays the words of the command after history substitution

HELPFUL HINTS

You can see the value of user variables by using the set command. The env command can be used to display the values of the system variables.

REFERENCES/MANUALS

InfoExplorer provides online help regarding the C shell

Many books exist in the library and your local bookstore that cover AIX (UNIX) and the C shell. Search through these for one that explains the amount of information you need at a level corresponding to your expertise with AIX.

(c) Copyright UCF Computer Services I& R Support 07/27/93