View this PageEdit this Page (locked)Uploads to this PageHistory of this PageTop of the SwikiRecent ChangesSearch the SwikiHelp Guide

unix shell intro

Introduction to Unix Shells

Introduction to Unix Shells


Contents

Please note that in order to view this page properly, you must use a Web browser which supports tables. For instance, Netscape V1.1 (or better) or Mosaic V2.6 for UNIX (or better).


This page provides a brief overview of Unix shells, and provides information on using the POSIX and C shells on the Cray. It does not cover programming aspects of using shells in much detail. Users should consult a standard Unix text for more information on using shells.

What is a Unix Shell?

A shell is a user interface which acts as an interpreter between the user and the Unix operating system kernel. A shell is both a command interpreter and a programming language. As a command interpreter, it examines and processes the commands you type, executes its built-in commands, and passes other commands on to the Unix operating system for execution. As a programming language, it processes commands stored in files known as shell scripts.

A Brief History of Unix Shells

A Unix shell is simply a Unix program and is separate from the operating system. Due in part to this separation of shell and operating system, many different shells have been written for Unix. There are two main families of shells - the Bourne shell and the C shell families. Members of the Bourne shell family include the Korn shell (ksh), the POSIX shell (sh), the Bourne Again Shell (bash), and the Z shell (zsh). The Tenex C Shell (tcsh) belongs to the C shell family.

The Bourne shell was written by Steven R. Bourne, and was the first Unix shell. Its interpretive programming language includes all the features that are commonly considered to produce structured programs. It does not include many features which are desirable to interactive users.

When the University of California at Berkeley was granted a license to port and extend Unix, their BSD (Berkeley System Distribution) version of Unix included a new shell, the C shell, which added many useful new interactive features such as job control, history, and aliasing. The new shell was called the C shell because its programming language resembles the C language. Unfortunately, the C shell is not as robust as the Bourne shell so people who use the C shell for interactive use usually write shell programs using a shell from the Bourne family.

The Tenex C shell was developed to fix some of the bugs in the C shell and to add more interactive features such as command line editing.

David Korn from AT&T developed the Korn shell, which maintains compatibility with the Bourne shell's programming language and extends it, while adding many of the C shell's nice interactive features. The Korn shell provides good support for both interactive use and programming, and has become a standard part of Unix System V. The POSIX standard, an effort to provide a standard programming environment based on Unix, has specified a shell, called the POSIX shell, that is very similar to the Korn shell. One key difference between two shells is that the Korn shell pattern matching feature is not available in the Posix shell.

Shells Supported on the Cray

This page addresses the POSIX and C shells in particular; they are the two supported shells on the Cray. In addition to the POSIX and C shells, the Korn and Tenex C shell are available on the Cray. The Tenex C shell (tcsh) is not officially supported by the software.

The default shell on the Crays is the POSIX shell, called sh, which new users get automatically. It is possible to change your default shell by using the chsh command.

Choosing the Right Shell for You

Choosing a default shell is largely a matter of personal taste, but here are some guidelines in selecting a shell:

How to Change Your Default Shell on the Cray

You may change your default login shell by using the following command:

chsh userid shell

where userid is your NCCS userid and shell is one of the following:

shell shell name
/bin/sh POSIX shell
/bin/csh C shell
/bin/ksh Korn shell
/usr/local/ubin/tcsh Tenex C shell (unsupported)

For example, to change your default shell to the C shell, issue:

chsh userid /bin/csh

Note: Any changes to the default shell on charney will be made on suomi when the password files are synchronized. If the password files are not synchronized and you have your .rhosts file set up, then you can use the following remote shell command:

remsh suomi chsh userid shell

Overview of the POSIX Shell

The POSIX Shell and Telnet

A word of warning: if you are not using a modern, linemode version of telnet to access the Cray, you are likely to run into screen line wrap problems using the POSIX shell. Screen line wrap problems look like this:

charney-> history
370     cat profile.old
                       371      cat profile.old
                                               372      ls
                                                          373   cat
tes*

374    cat test test1
             375        cat test
                                376     cat test1
                                                 377    ls -C

To fix this problem, issue the following command:

stty -extproc

Note: You can check your version of telnet as follows:

  1. Type the telnet remote_host command, for example:

    telnet charney

  2. Type the telnet escape character sequence, usually Control-] ( press the control and ] keys simultaneously).

  3. Type the telnet status command:

    status

If you see the message "Operating in character-at-a-time mode" or "Operating in line-by-line mode" you are using an old version of telnet. If you see "Operating with LINEMODE option" you are using a modern version of telnet. If possible, try to have your system administrator obtain a modern version of telnet for your workstation.

Using Aliases as a Shorthand

The alias command allows you to define aliases for commands. For example:

alias cx='chmod u+x'

Once you've defined the above alias, you can type cx instead of chmod u+x. If you type:

cx filename

it is as though you had typed:

chmod u+x filename

Aliases are usually defined in your environment file (see the section on startup files, below). Some aliases are defined for you by the POSIX shell. To see what aliases are in effect, type alias. To remove an alias, type:

unalias alias_name

The POSIX Shell cd Command

You can use the POSIX shell cd command in the following ways:

cd cd to your home directory
cd - cd to the previous directory
cd complete_pathname cd to the directory complete_pathname
cd partial_pathname cd uses CDPATH to search for a pathname that includes partial_pathname. If CDPATH isn't defined, only the working directory is searched. See the section on environment variables, below, for information on CDPATH.
cd old new cd substitutes the first occurrence of the string old with the string new in the working directory name, and attempts to cd to the resulting directory.

Tilde (~) Substitution

The tilde, ~, can be used to refer to your home directory, and ~another_userid refers to the home directory of user another_userid.

For example, from any directory you could issue the command:

cp ~/filename .

to copy the file filename from your home directory to your working directory.

You can use ~+ to refer to the pathname of your working directory, and ~- to refer to the pathname of your previous working directory.

Redirecting Standard Error

You can use >2 to redirect standard error (error messages) to a file. Suppose you wanted to save the error messages from the f90 command in a file. You could type:

f90 program.f >2 program.errors

If you want to redirect both the standard output and the standard error to the same file, type:

f90 program.f > program.out 2>&1

Job Control

You can execute a command in the background by terminating the command line with an &. This allows you to proceed with other work in the foreground while the background job executes. For example, if you have a time consuming compilation to perform, you may wish to run it in the background, as follows:

f90 big_program.f &

If you have already started a process, and wish to place it in the background, press [Control]-z (hold the Control key, then press the z key) to stop the job, then type bg to place it in the background.

To see the jobs you are currently running, type jobs. You will see a display like:

   [1] +  Running                 f90 big_program.f &

where the number between square brackets is the job number.

To bring a job running in the background to the foreground, type:

fg %#

where # is the job number.

If a background job attempts to read from the terminal, the POSIX shell will stop it. You must then move that job to the foreground so that it can read from the terminal.

Command Substitution

You may want to use the output of one command as the argument to another command. You can do command substitution by putting a command inside $(). For example, suppose you wanted to know the date on which the ftp command was installed on your system, but you didn't know the pathname of the ftp binary. The built-in POSIX shell command whence provides information on the pathname. You could type:

ls -l $(whence ftp)

The POSIX shell substitutes $(whence ftp) with /usr/ucb/ftp, and displays the following on your screen:

   -rwxr-xr-x   1 bin      bin       575416 Aug 29  1993 /usr/ucb/ftp

Note: Command substitution occurs inside double quotes (" ... "), but not inside single quotes (' ... ').

The Command History Mechanism

The POSIX shell keeps a log, or history, of your most recently entered commands. Some commands to use with history are:

history Displays the last 16 commands.
history -25 Displays the last 25 commands.
r Re-execute the previous command.
r 101 Re-execute the command numbered 101.
r string Re-executes the last command that starts with string. For example, r l would re-execute the last command starting with the letter l.
r old=new string Re-executes the last command that starts with string, replacing the first occurrence of the string old with new.

The HISTSIZE variable lets you define how long this history list should be; if it is not set, the default is 128 commands. The HISTFILE variable identifies the file this list is stored in; if it is not set, the history list is stored in .sh_history in your home directory.

In addition to the commands listed above, you can use the fc (fc stands for "fix command") command or the built-in editor to access and edit any command in the history list. Note that the history command is actually a built-in alias for fc -l, and the r command is a built-in alias for fc -e. For more information on fc, see the man pages for sh.

Command Line Editing

If you have set either the VISUAL or the EDITOR variable (see the section "Environment Variables", below) to the pathname of the vi or emacs editor, you will be able to use command line editing. Alternatively, you can use the set -o command with either the vi or the emacs option. Command line editing allows you to correct the command you are typing, by using the POSIX shell built-in editor, either the vi built-in editor, or the emacs built-in editor. You can also retrieve a command from the history file, change it, and execute it.

Only the built-in vi editor is described here. Its commands consist of a subset of the vi editor's commands. This page assumes that you are familiar with the vi editor. Note that the arrow keys do not work with the POSIX shell built-in vi editor.

Some useful built-in vi commands are:

[count]h Moves the cursor 1 (or count) character(s) to the left.
[count]l Moves the cursor 1 (or count) character(s) to the right.
[count]b Moves the cursor 1 (or count) word(s) to the left.
[count]w Moves the cursor 1 (or count) word(s) to the right.
i Inserts text before the cursor; press the Escape key to terminate insert mode or press Enter to execute the modified command.
a Inserts text after the cursor; press Escape or Enter to terminate.
A Appends text to the end of the line.
[count]x Deletes 1 (or count) character(s).
[count]r Replaces 1 (or count) character(s).
[count]cw Changes 1 (or count) words.
R Replaces text until you press Escape or Enter.
u Undoes the last modification.
U Undoes all modifications.
* Does filename generation.
\ Does filename completion.

To make a correction to the command you are typing, hit the Escape key to enter vi's command mode. You can then use many of the normal vi commands to edit your command line. Press Enter or Return to execute the modified command.

Filename completion is a feature that allows you to type part of a filename, and the shell attempts to complete the filename. Suppose you wanted to cat the file named really.long.filename. You could do the following:

cat rea<Escape>\

where <Escape> stands for the Escape key. The sequence <Escape>\ tells the POSIX shell to try to complete the filename you started typing. If rea uniquely identifies the file really.long.filename, you will see the following on the screen:

cat really.long.filename

Just press Enter to execute the command. If rea does not uniquely identify the file, because you also have a file named reality, say, the POSIX shell will complete the filename as far as it can. In this case you would see:

cat real

You could then supply another "l" and press <Escape>\ again:

cat reall<Escape>\

and the shell would be able to complete the filename.

Command line editing can also be applied to the history file. While in editor command mode (hit the Escape key to get there), you can retrieve a command from the history file by using one of the following vi commands:

[count]k Fetches the previous (count) command.
[count]- Same as [count]k.
[count]j Fetches the next (count) command.
[count]+ Same as [count]j.
[count]G Fetches command number count. If count is not specified, it defaults to the least recent history command, unlike in "real vi" where G means the last line in the file.
/string Searches backward in the history file for a previous command containing string. Press the Return key to run this command. If string is preceded by a caret (^) then the matched command must begin with string.
?string Searches forward in the history file.

Writing POSIX Shell Scripts

A shell script is a file that contains commands to be executed by the shell. The easiest way to run a shell script is to type its name on the command line. In order to be able to do that, be sure that:

  1. You have included the working directory in your PATH (see the section on startup files, below).

    If you do not have the working directory in your PATH, you can execute a file in your working directory for which you have execute permission by typing:

    ./shell_script_name

  2. You have set the read and execute bits:

    chmod u+xr shell_script_name

    If you have the working directory in your PATH, you can execute a file which doesn't have the execute bit set by typing:

    . shell_script_name

    or:

    sh shell_script_name

Comments are preceded by a pound sign, #. For example:

# This is a comment.

If you need to enter a long command line, you can use the backslash, /, to continue the command to the next line.

Here documents are often used in shell scripts to allow the script to provide responses to commands designed for interactive use. For example:

   /usr/local/bin/ultra/ftp -i dirac-h 1021 <<EOF
   cd my_UniTree_directory
   get my_UniTree_file
   quit
   EOF

Variables may be defined with statements of the form:

variable_name=value

Note that there must be no space on either side of the = sign. Once a variable has been given a value, you can retrieve its value by preceding its name with a $, for example:

print $variable_name

One of the simplest flow control construct is the if/then/else/fi construct:

   if condition
   then
      statements
   else
      statements
   fi

For example:

   # Check to see if the DMF daemon is running
   dmfstat
   RTCODE=$?
   if [ "$RTCODE" -ne 0 ]; then
      exit
   # If silo daemon is found, continue processing
   else
      cd /silo/usrid/subdir1
      more mydata
   fi

In the above example:

The POSIX shell provides other flow control commands, such as:

   if then elif else fi
   for do done
   while do done
   until do done
   case in esac
   select in done

It is beyond the scope of this page to discuss shell programming in detail. Please consult a Unix or Korn Shell text for more information.

Environment Variables

An environment variable is a variable that defines characteristics of your shell environment. They are also called shell variables or shell parameters. The more commonly used POSIX shell environment variables on the Cray are listed below:

CDPATH Specifies a list of directories for the cd command to search through, allowing you to use partial filenames with cd. If CDPATH is not set, and you specify a partial pathname, cd assumes that you are referring to a subdirectory of the working directory. (similar to PATH for commands).
COLUMNS Identifies the number of columns on your screen or window. By default it is 80. To force COLUMNS to pick up the actual number of columns, type: eval $(resize)
DISPLAY Defines the name of your workstation or terminal, so that X programs know where to send their displays.
EDITOR Defines your preferred editor, usually vi or emacs.
ENV Defines the file that will be executed by the POSIX shell each time a new shell is started.
FCEDIT Defines the editor the fc command uses. If not set, the default is /bin/ed.
HISTFILE Names the file used to store the history list. If not set, the POSIX shell uses .sh_history in your home directory.
HISTSIZE Defines the number of commands kept in the history list. If not set, the default is 128.
HOME The working directory you get when you first log on. On the Cray, its name is /u#/your_userid , where # is 1, 2, 3, or 4. If you issue the cd command without an argument, you go to your home directory.
LINES Identifies the number of lines on your screen or window. By default it is 24. To force LINES to pick up the actual number of lines, type:

eval $(resize)

PATH Tells the shell where to look for commands, so that you don't have to type complete pathnames. The Cray automatically includes /bin, /usr/bin, /usr/ucb, and /usr/local/bin in your path. See the section on startup files for information on including your working directory in your PATH.
PRINTER Defines the default printer.
PS1 Sets the appearance of your prompt.
PS2 Sets the secondary prompt, which by default is >. The secondary prompt is used if you enter an incomplete command; it prompts you to complete the command.
PWD "Print Working Directory": displays the working directory.
TERM Defines your terminal type.
TMPDIR Defines a special temporary file directory that UNICOS creates for each user login session and for each NQS batch job. UNICOS automatically removes the $TMPDIR directories when the login session or NQS job terminates.
VISUAL Defines the editor to use for command line editing. If not set, the editor defined by EDITOR is used.

Customizing Your POSIX Shell Environment - Startup Files

If the POSIX or Bourne shell is your default shell, when you log into the Cray the file /etc/profile is executed. This file contains commands that are executed by the system for all POSIX and Bourne shell users. For example, a default PATH is defined, a default prompt is set, and a default umask (file creation mask) is set.

After that, if you have a .profile file in your home directory , it is executed. This is one of the places where you can customize your environment. Another startup file for the POSIX shell is the environment file, which is executed whenever a POSIX subshell starts. See the section "Sample .envfile" for more information on the uses of the environment file.

Sample .profile

A sample .profile file, executed when you first log in and start a session, is shown below.

 
#!/bin/sh
#------------------------
# A sample .profile file.
#------------------------

# Add to the default search PATH (. represents the current directory).
export PATH=$PATH:$HOME/bin:/usr/bin/X11:/etc:/usr/local/lib:/usr/local/bin/usr/loc

# Initialize for Cray's Programming Environment (Modules)
if  [ -f /opt/modules/modules/init/ksh ] ; then
     # Initialize modules
     . /opt/modules/modules/init/ksh
     module load modules PrgEnv
fi

# The system default for the umask is 077, i.e rwx------.
# Set your default file permissions to rwxr-x---.
umask 027
# Or, to set your default file permissions to rwxrwxr-x, uncomment:
#umask 002

# Set prompt to show history number and current directory.
export PS1="[!] \$PWD -> "

# Set the environment variable for NCAR Graphics.
export NCARG_ROOT=/usr/local

# Set default printer for printing to your local network attached
# printer.  The printer must have an entry in charney's /etc/printcap
# file.  Call the TAG to set this up.
export PRINTER=my_printer_name

export ENV=$HOME/.envfile    # ENV defines the environment file.

# Is this an interactive or an NQS batch session?
if [ "ENVIRONMENT" == "BATCH" ]
then # NQS Batch setup

   set -vx  # Display commands and the interpreted versions

else # Interactive setup

   stty -extproc        # Prevent jagged line wrap problems; use this
                        # option only if you have line wrap problems.
   eval $(resize)       # Capture the login session's window size.

   # Set default editor -- choose between vi and emacs.
   export EDITOR=$(whence vi)
   #export EDITOR=$(whence emacs)

   # Set Command Line editor -- choose between vi and emacs.
   export FCEDIT=$(whence vi)
   #export FCEDIT=/$(whence emacs)

   # Set history size.
   export HISTSIZE=50   # Keep 50 entries in the history list.

   # Set DISPLAY if using X windows.  Replace display with the name of
   # your workstation or X-terminal.
   export DISPLAY=myworkstation.gsfc.nasa.gov:0.0
fi
This .profile does the following:

  1. It adds additional pathnames to the PATH set up in /etc/profile. You should always add to the PATH, rather than redefine it (this way your path will always include the default pathnames defined by the system). Pathnames are separated by a colon, :. The last dot at the end of the PATH refers to the working directory. Including the working directory in your PATH allows you to execute commands and shells in your working directory be referring to them by their simple filenames (so long as the correct execute bit is set). The export command means that all subprocesses will know the value of PATH.

  2. Cray packages its compilers, programmers' libraries, and programming analysis tools into complete, integrated sets known as Programming Environments. On the Crays, we have three programming environments: FORTRAN 90, C++, and Message-Passing Toolkit. By loading the PrgEnv module, you access all three programming environments on the Crays. This is necessary to access the Fortran compiler, the C compilers, the TotalView debuggers, etc. See our web page: Accessing Cray's Programming Environments for more information.

  3. It sets the file creation mask to 027, meaning that directories will be created with a file permission of rwxr-x---, and plain files with a file permission of rw-r-----. Alternatively, you can set your umask to 022.

  4. It sets your prompt (using the PS1 environment variable) to show the history number of the current command, followed by the pathname of the current directory.

  5. It defines an environment variable needed by NCAR Graphics.

  6. It defines the default printer name, used with the lpr command. Note that for this to work on the Cray, your printer name must be defined in the Cray's /etc/printcap file. See Printing Files from the NCCS Cray using lpr for more information.

  7. ENV defines the environment file to be .envfile. This file is executed whenever a new POSIX shell begins execution. A sample environment file is shown below.

  8. For NQS batch jobs, it sets the v and x options, so that shell input lines are printed as they are read, and commands are printed as they are executed. The set command is used to set options.

  9. For interactive login sessions, it:

Sample .envfile

You can also have an environment file which will execute if the ENV environment variable is set and whenever a new POSIX shell is executed. A sample environment variable is shown below. While variables that are exported are known to subprocesses, non-exported variables, aliases, and options must be specifically communicated to subprocesses, which you do in the environment file.


#! /bin/sh
#------------------------
# A sample .envfile file.
#------------------------

# Set up aliases
#---------------
alias rm='rm -i'           # Ask before deleting.
alias h='fc -l'            # Use h for history.
alias l='ls -al'           # Give long listing and show hidden files.
alias list='ls -alt'       # Give long listing sorted by date.
alias lm='ls -alt | more'  # Long listing with pause at each screenful.
alias lc='ls -C'           # Give short listing using column output.
alias lh="ls -a | grep ^'\.' | more" # List hidden files only.

# Set options
#------------
set -o noclobber               # Prevents file overwrite when using >;
                               # use >| to overwrite an existing file.
set -o ignoreeof               # Don't let <Control>d cause exit.

This .envfile does the following:

  1. Defines seven aliases.

  2. Sets the noclobber and ignoreeof options.

List of POSIX Shell Built-in Commands

The POSIX shell on the Crays has the following built-in commands. See the man page for sh, or a Unix or Korn shell text for more information.

alias bg break cd echo
eval exec exit export fc
fg getopts jobs kill let
print pwd read read readonly
return set shift times trap
typeset ulimit umask unalias unset
wait whence : .

Overview of the C Shell

The C shell includes many, but not all, of the Korn shell's features, although they are sometimes implemented differently. It also includes features, such as directory stack manipulation, that are not in the Korn shell.

Using Aliases as a Shorthand

The alias command allows you to define aliases for commands. For example:

alias cx 'chmod u+x'

Once you've defined the above alias, you can type cx instead of chmod u+x. If you type:

cx filename

it is as though you had typed:

chmod u+x filename

Aliases are usually defined in your .cshrc file (see the section on startup files, below). To see what aliases are in effect, type alias. To remove an alias, type:

unalias alias_name

Tilde (~) Substitution

The tilde, ~, can be used to refer to your home directory, and ~another_userid refers to the home directory of user another_userid.

For example, from any directory you could issue the command:

cp ~/filename .

to copy the file filename from your home directory to your working directory.

Redirecting Standard Error

Unlike the Korn shell, you cannot redirect standard error (error messages) to a file separately from standard output. You can, however, combine standard error and standard output, and redirect both to a file using >&. For example, to save the error messages from the f90 command in a file you could type:

f90 program.f >& program.errors

Job Control

You can execute a command in the background by terminating the command line with an &. This allows you to proceed with other work in the foreground, while the background job executes. For example, if you have a time consuming compilation to perform, you may wish to run it in the background, as follows:

f90 big_program.f &

If you have already started a process, and wish to place it in the background, press <Control>-z (press the Control and z keys simultaneously) to stop the job, then type bg to place it in the background.

To see the jobs you are currently running, type jobs. You will see a display like:

   [1] +  Running                 f90 big_program.f &

where the number between square brackets is the job number.

To bring a job running in the background to the foreground, type:

fg %#

where # is the job number.

If a background job attempts to read from the terminal, the C shell will stop it. You must then move that job to the foreground so that it can read from the terminal.

Command Substitution

You may want to use the output of one command as the argument to another command. You can do command substitution by putting a command between back quotes. For example, suppose you wanted to know the date on which the ftp command was installed on your system, but you didn't know the pathname of the ftp binary. The built-in C shell command which provides information on the pathname. You could type:

ls -l `which ftp`

The C shell substitutes `which ftp` with /usr/ucb/ftp, and displays the following on your screen:

   -rwxr-xr-x   1 bin      bin       575416 Aug 29  1993 /usr/ucb/ftp

Note: Command substitution occurs inside double quotes (" ... "), but not inside single quotes (' ... ').

The Command History Mechanism

Unlike the Korn shell, the C shell does not automatically maintain a history list of your most recently executed commands. To activate history in the C shell, use the set history command:

set history = #

where # is the number of history commands to save. The set command is usually issued in your .cshrc file (see the section on startup files, below).

To save history between login sessions, use:

set savehist = #

where # is the number of commands you want the C shell to save.

history Displays all the commands in the history list.
history 25 Displays the last 25 commands.
!! Re-executes the previous command.
!42 Re-executes the command numbered 42 in the history list.
!string Re-executes the last command that starts with string. For example, !l would re-execute the last command starting with the letter l.
^old^new Re-executes the previous command, replacing the first occurrence of the string old with new.

Note that !! (re-execute the previous command) is always available, even if you haven't enabled history.

Directory Stack Manipulation

The C shell can store a list of the directories you are using in a stack, making it easy for you to switch directories without having to type long pathnames. To start the directory stack, and place the working directory on the top of the stack, type:

dirs

The C shell responds by displaying your working directory (using ~ to represent your home directory).

To change to a new directory and add the new directory to the top of the stack, type:

pushd new_directory

The C shell responds by showing all the directories you have on the stack.

To switch back and forth between the top two directories on the stack, type pushd (without an argument). pushd cd's you to the second directory on the stack, and makes it the new top directory. The old top directory becomes the new second directory on the stack.

To remove a directory from the stack, type popd. popd removed the top directory from the stack, and cd's you to the next directory on the stack (which becomes the new top directory).

Writing C Shell Scripts

A shell script is a file that contains commands to be executed by the shell. The easiest way to run a shell script is to type its name on the command line. In order to be able to do that, be sure that:

  1. You have included the working directory in your PATH (see the section on startup files, below).

    If you do not have the working directory in your PATH, you can execute a file by typing:

    source shell_script_name

  2. You have set the read and execute bits:

    chmod u+xr shell_script_name

    You can execute a file which doesn't have the execute bit set by typing:

    source shell_script_name

Comments are preceded by a pound sign, #. For example:

# This is a comment.

If you need to enter a long command line, you can use the backslash, /, to continue the command to the next line.

Here documents are often used in shell scripts to allow the script to provide responses to commands designed for interactive use. For example:

   /usr/local/bin/ultra/ftp -i dirac-h 1021 <<EOF
   cd my_UniTree_directory
   get my_UniTree_file
   quit
   EOF
 

Variables may be defined with statements of the form:

set variable_name = value

Once a variable has been given a value, you can retrieve its value by preceding its name with a $, for example:

print $variable_name

One of the simplest flow control construct is the if/then/else/endif construct:

   if condition then
      statements
   else
      statements
   endif
 

For example:

   # Check to see if the DMF daemon is running 
   dmfstat
   set RTCODE = $status
   if ( "$RTCODE" != 0 ) then
      exit
   # If silo daemon is found, continue processing
   else
      cd /silo/usrid/subdir1
      more mydata
   endif

In the above example:

The C shell provides other flow control commands, such as:

It is beyond the scope of this page to discuss shell programming in detail. Please consult a Unix or C Shell text for more information.

Environment Variables

An environment variable is a variable that defines characteristics of your shell environment. They are also called shell variables or shell parameters. The more commonly used C shell environment variables on the Cray are listed below:

cdpath Specifies a list of directories for the cd command to search through, allowing you to use partial filenames with cd. If cdpath is not set, and you specify a partial pathname, cd assumes that you are referring to a subdirectory of the working directory. (similar to PATH for commands).
COLUMNS Identifies the number of columns on your screen or window. To set COLUMNS, type: eval `resize`
cwd Provides the full path name of the current directory.
DISPLAY Defines the name of your workstation or console, so that X programs know where to send their displays to.
EDITOR Defines your preferred editor, usually vi or emacs.
history Defines the size of the history list, and activates the history mechanism.
HOME The working directory you get when you first log on. On the Cray, its name is /u#/your_userid, where # is 1, 2, 3, or 4. If you issue the cd command without an argument, you go to your home directory.
LINES Identifies the number of lines on your screen or window. To set LINES, type: eval `resize`
ignoreeof If set, prevents the shell from being accidentally killed by a <Control-d>.
noclobber If set, prevents files from being overwritten by output redirection (>), and requires that >> redirections refer to existing files. Use >! to overwrite an existing file, and >>! to "append" to a nonexistent file.
PATH Tells the shell where to look for commands, so that you don't have to type complete pathnames. The Cray automatically includes /bin, /usr/bin, /usr/ucb, and /usr/local/bin in your path. See the section on startup files, below, for information on including your working directory in your PATH.
PRINTER Defines the default printer.
prompt Sets the appearance of your prompt.
savehist If set, controls the number of entries that are saved in /.history when you log out.
status The status returned by the last command. If it terminated abnormally, 0200 is added to the status. Built-in commands that fail return a status of 1.
TERM Defines your terminal type.
TMPDIR Defines a special temporary file directory that UNICOS creates for each user login session and for each NQS batch job. UNICOS automatically removes the $TMPDIR directories when the login session or NQS job terminates.

Environment Variable Substitution

Use $variable_name to display the value of variables. For example:

echo $PATH

would display something like:

   /bin:/usr/bin:/usr/ucb:/usr/local/bin:/usr/bin/X11:/etc:.

Note: Variable substitution occurs inside double quotes (" ... "), but not inside single quotes (' ... ').

Customizing Your C Shell Environment - Startup Files

If the C shell is your default shell, when you log into the Cray the file /etc/cshrc is executed. This files contains commands that are executed by the system for all C shell users. For example, a default PATH is defined, a default prompt is set, and a default umask (file creation mask) is set.

After that, if you have a .cshrc file in your home directory, it is executed. The .cshrc is executed whenever a new C shell starts. Finally, if you have a .login file in your home directory and if your shell is a login shell, the .login is executed. The .login and .cshrc are two places where you can customize your C shell environment.

The .login contains commands you want to execute once, at the beginning of each login session. Remember that this file is executed only if the shell is a login shell. If you want a telnet session to execute your .login, use the -ls telnet option to indicate that the telnet session should be considered as a login session. (An alternative is not to use a .login file, but only a .cshrc file.)

Sample .login

A sample .login file, executed (after the .cshrc file) when you first log in and start a session, is shown below.


#!/bin/csh
#----------------------
# A sample .login file.
#----------------------

# The system default for the umask is 077, i.e rwx------.
# Set your default file permissions to rwxr-x---.
umask 027
# Or, to set your default file permissions to rwxrwxr-x, uncomment:
#umask 002

# Set prompt to show history number and current directory.
set prompt="[\!] $cwd-> "
alias cd 'cd \!*;set prompt="[\\!] $cwd -> "'

# Set the environment variable for NCAR Graphics.
setenv NCARG_ROOT /usr/local

# Set default printer for printing to your local network attached
# printer.  The printer must have an entry in charney's /etc/printcap
# file.  Call the TAG to set this up.
setenv PRINTER my_printer_name

# Is this an interactive or an NQS batch session?
if ($?ENVIRONMENT) then # NQS batch session

   set timestamp     # Mark date/time of commands
   set echo verbose  # Show commands and results as they execute

else  # Interactive session

   eval `resize`     # Capture the login session's window size.

   # Set the default editor -- choose between vi and emacs.
   setenv EDITOR `which vi`
   #setenv EDITOR ` which emacs`

   # Set DISPLAY if using X windows.  Replace display with the name of
   # your workstation or X-terminal.
   setenv DISPLAY myworkstation.gsfc.nasa.gov:0.0

endif

This sample .login does the following:

  1. It sets the file creation mask to 027, meaning that directories will be created with a file permission of rwxr-x---, and plain files with a file permission of rw-r-----. Alternatively, you can set your umask to 022.

  2. It sets the prompt to display both the history event number and the working directory (the latter requires aliasing the cd command).

  3. It defines an environment variable needed by NCAR Graphics.

  4. It defines the default printer name, used with the lpr command. Note that for this to work on the Crays, your printer name must be defined in the Cray's /etc/printcap file. See Printing Files from the NCCS Cray using lpr.

  5. For NQS batch jobs, it sets the timestamp, echo and verbose options.

  6. For interactive login sessions, it captures the login session's window size (so that commands like vi and more work properly), sets your preferred editor to vi, and sets the DISPLAY to your workstation, so that X programs you run on the Cray know where to send their display.

Sample .cshrc

A sample .cshrc file, executed whenever a new C shell starts, is shown below. It contains commands to establish variables and commands that are local to a specific shell.


#!/bin/csh
#----------------------
# A sample .cshrc file.
#----------------------

# Add to the default search PATH (. represents the current directory).
setenv PATH ${PATH}:$HOME/bin:/usr/bin/X11:/etc:/usr/local/lib:.

# Initialize for Cray's Programming Environment (Modules)
if  [ -f /opt/modules/modules/init/csh ] ; then
     # Initialize modules
     source /opt/modules/modules/init/csh
     module load modules PrgEnv
endif

# Set up aliases
#---------------
alias rm   'rm -i'          # Ask before deleting.
alias log  'logout'         # Use log to logout.
alias h    'history'        # Use h for history.
alias l    'ls -al'         # Give long listing and show hidden files.
alias list 'ls -alt'        # Give long listing sorted by date.
alias lm   'ls -alt | more' # Long listing with pause at each screenful.
alias lc   'ls -C'          # Give short listing using column output.
alias lh   "ls -a | grep ^'\.' | more" # List hidden files only.


# Set Options
#------------
set history=50              # Keep 50 entries in the history list.
set savehist=50             # Save last 50 commands between logins.
set noclobber               # Prevents file overwrite when using >;
                            # use >! to overwrite an existing file
                            # and >>! to "append" to a nonexistent file.
set ignoreeof               # Don't let <Control>d cause logout.

This .cshrc does the following:

  1. It adds additional pathnames to the PATH set up in /etc/cshrc. You should always add to the PATH, rather than redefine it (this way your path will always include the default pathnames defined by the system). Pathnames are separated by a colon, :. The last dot at the end of the PATH refers to the working directory. Including the working directory in your PATH allows you to execute commands and shells in your working directory be referring to them by their simple filenames (so long as the correct execute bit is set).

  2. Cray packages its compilers, programmers' libraries, and programming analysis tools into complete, integrated sets known as Programming Environments. On the Crays, we have three programming environments: FORTRAN 90, C++, and Message-Passing Toolkit. By loading the PrgEnv module, you access all three programming environments on the Crays. This is necessary to access the Fortran compiler, the C compilers, the TotalView debuggers, etc. See our web page: Accessing Cray's Programming Environments for more information.

  3. Defines nine aliases.

  4. Sets the noclobber and ignoreeof options.

List of C Shell Built-in Commands

The C shell on the Crays has the following built-in commands. See the man page for csh, or a Unix or C shell text for more information.

alias bg break breaksw case
cd chdir continue default dirs
dmmode echo else end endif
endsw eval exec exit fg
foreach glob goto history if
jobs kill logout nice nohup
notify onintr popd pushd rehash
repeat set setenv shift source
stop suspend switch time umask
unalias unhash unset unsetenv wait
which while % @

References

The following were used as references:


Author: NCCS Technical Assistance Group (tag@nccs.gsfc.nasa.gov)
Authorizing Technical Official: Michael S. Seablom, NASA/GSFC Code 931 (Michael.S.Seablom.1@gsfc.nasa.gov)
Authorizing NASA Official: Nancy Palm, NASA/GSFC Code 931 (Nancy.L.Palm.1@gsfc.nasa.gov)
Last Updated: 07/08/99
Reason: Added semicolons to & in code.





Links to this Page