home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


5.3 Variables

This section describes the following:

  • Variable substitution

  • Variable modifiers

  • Predefined shell variables

  • Example .cshrc file

  • Environment variables

5.3.1 Variable Substitution

In the following substitutions, braces ({} ) are optional, except when needed to separate a variable name from following characters that would otherwise be a part of it.

${ var } The value of variable var .
${ var [ i ]}

Select word or words in position i of var . i can be a single number, a range m -n , a range - n (missing m implies 1), a range m - (missing n implies all remaining words), or * (select all words). i can also be a variable that expands to one of these values.

${# var } The number of words in var .
${#argv} The number of arguments.
$0 Name of the program. (Usually not set in interactive shells.)
${argv[ n ]}

Individual arguments on command line (positional parameters). n = 1-9.

${ n }

Same as ${argv[ n ]} .

${argv[*]} All arguments on command line.
$* Same as $argv[*] .
$argv[$#argv] The last argument.
${? var }

Return 1 if var is set; 0 if var is not set.

$$

Process number of current shell; useful as part of a filename for creating temporary files with unique names.

$?0 Return 1 if input filename is known; 0 if not.
$< Read a line from standard input.

5.3.1.1 Examples

Sort the third through last arguments (files) and save the output in a unique temporary file:

sort $argv[3-] > tmp.$$

Process .cshrc commands only if the shell is interactive (i.e., the prompt variable must be set):

if ($?prompt) then
   set commands,

   alias commands,

   etc.

endif

5.3.2 Variable Modifiers

Except for $? var , $$ , $?0 , and $< , the previous variable substitutions may be followed by one of the following modifiers. When braces are used, the modifier goes inside them.

:r

Return the variable's root.

:e

Return the variable's extension.

:h

Return the variable's header.

:t

Return the variable's tail.

:gr

Return all roots.

:ge

Return all extensions.

:gh

Return all headers.

:gt

Return all tails.

:q

Quote a wordlist variable, keeping the items separate. Useful when the variable contains filename metacharacters that should not be expanded.

:x

Quote a pattern, expanding it into a wordlist.

5.3.2.1 Examples using pathname modifiers

This table shows the use of pathname modifiers on the following variable:

set aa=(/progs/num.c /book/chap.ps)

Variable Portion Specification Output Result
Normal variable echo $aa /progs/num.c /book/chap.ps
Second root echo $aa[2]:r /book/chap
Second header echo $aa[2]:h /book
Second tail echo $aa[2]:t chap.ps
Second extension echo $aa[2]:e ps
Root echo $aa:r /progs/num /book/chap.ps
Global root echo $aa:gr /progs/num /book/chap
Header echo $aa:h /progs /book/chap.ps
Global header echo $aa:gh /progs /book
Tail echo $aa:t num.c /book/chap.ps
Global tail echo $aa:gt num.c chap.ps
Extension echo $aa:e c /book/chap.ps
Global extension echo $aa:ge c ps

5.3.2.2 Examples using quoting modifiers

% set a="[a-z]*" A="[A-Z]*"


% echo "$a" "$A"


[a-z]* [A-Z]*

% echo $a $A


at cc m4 Book Doc

% echo $a:x $A


[a-z]* Book Doc

% set d=($a:q $A:q)


% echo $d


at cc m4 Book Doc

% echo $d:q


[a-z]* [A-Z]*

% echo $d[1] +++ $d[2]


at cc m4 +++ Book Doc

% echo $d[1]:q


[a-z]*

5.3.3 Predefined Shell Variables

Variables can be set in one of two ways, by assigning a value:

set var
=value

or by simply turning them on:

set var

In the following table, variables that accept values are shown with the equals sign followed by the type of value they accept; the value is then described. (Note, however, that variables such as argv , cwd , or status are never explicitly assigned.) For variables that are turned on or off, the table describes what they do when set. The C shell automatically sets the variables argv , cwd , home , path , prompt , shell , status , term , and user .

Variable Description
argv=( args )

List of arguments passed to current command; default is () .

cdpath=( dirs )

List of alternate directories to search when locating arguments for cd , popd , or pushd .

cwd= dir

Full pathname of current directory.

echo

Redisplay each command line before execution; same as csh -x command.

fignore=( chars )

List of filename suffixes to ignore during filename completion (see filec ).

filec

If set, a filename that is partially typed on the command line can be expanded to its full name when the Escape key is pressed. If more than one filename matches, type EOF to list possible completions.

hardpaths

Tell dirs to display the actual pathname of any directory that is a symbolic link.

histchars= ab

A two-character string that sets the characters to use in history-substitution and quick-substitution (default is !^ ).

history= n

Number of commands to save in history list.

home= dir

Home directory of user, initialized from HOME . The ~ character is shorthand for this value.

ignoreeof

Ignore an end-of-file (EOF ) from terminals; prevents accidental logout.

mail=( n file )

One or more files checked for new mail every five minutes or (if n is supplied) every n seconds.

nobeep

Don't ring bell for ambiguous file completion (see filec ).

noclobber

Don't redirect output to an existing file; prevents accidental destruction of files.

noglob

Turn off filename expansion; useful in shell scripts.

nonomatch

Treat filename metacharacters as literal characters; e.g., vi ch* creates new file ch* instead of printing "No match."

notify

Notify user of completed jobs right away, instead of waiting for the next prompt.

path=( dirs )

List of pathnames in which to search for commands to execute. Initialized from PATH . SVR4 default is ( . /usr/ucb /usr/bin ) . On Solaris, the default path is ( /usr/bin . ) . However, the standard start-up scripts then change it to ( /bin /usr/bin /usr/ucb /etc . ) .

prompt=' str '

String that prompts for interactive input; default is % .

savehist= n

Number of history commands to save in ~/.history upon logout; they can be accessed at the next login.

shell= file

Pathname of the shell program currently in use; default is /bin/csh .

status= n

Exit status of last command. Built-in commands return 0 (success) or 1 (failure).

term= ID

Name of terminal type, same as TERM .

time=' n % c '

If command execution takes more than n CPU seconds, report user time, system time, elapsed time, and CPU percentage. Supply optional % c flags to show other data.

user= name

Login name of user, initialized from USER .

verbose

Display a command after history substitution; same as the command csh -v .

5.3.4 Example .cshrc File

# PREDEFINED VARIABLES
set path=(~ ~/bin /usr/ucb /bin /usr/bin . )
set mail=(/var/mail/tom)

if ($?prompt) then            # Settings for interactive use
  set echo
  set filec
  set noclobber ignoreeof

  set cdpath=(/usr/lib /var/spool/uucp)
# Now I can type cd macros 
# instead of cd /usr/lib/macros

  set fignore=.o              # Ignore object files for filec
  set history=100 savehist=25
  set prompt='tom \!% '       # Includes history number
  set time=3

# MY VARIABLES

  set man1="/usr/man/man1"    # Lets me do    cd $man1, ls $man1
  set a="[a-z]*"              # Lets me       do vi $a
  set A="[A-Z]*"              # Or            grep string $A

# ALIASES

  alias c "clear; dirs"       # Use quotes to protect ; or |
  alias h "history | more"
  alias j jobs -l
  alias ls ls -sFC            # Redefine ls command
  alias del 'mv \!* ~/tmp_dir'# A safe alternative to rm
endif

5.3.5 Environment Variables

The C shell maintains a set of environment variables , which are distinct from shell variables and aren't really part of the C shell. Shell variables are meaningful only within the current shell, but environment variables are automatically exported, making them available globally. For example, C shell variables are accessible only to a particular script in which they're defined, whereas environment variables can be used by any shell scripts, mail utilities, or editors you might invoke.

Environment variables are assigned as follows:

setenv VAR value

By convention, environment variable names are all uppercase. You can create your own environment variables, or you can use the following predefined environment variables.

These environment variables have a corresponding C shell variable:

HOME

Home directory; same as home . These may be changed independently of each other.

PATH

Search path for commands; same as path . Changing either one updates the value stored in the other.

TERM

Terminal type; same as term . Changing term updates TERM , but not the other way around.

USER

Username; same as user . Changing user updates USER , but not the other way around.

Other environment variables include the following:

EXINIT

A string of ex commands similar to those found in the startup .exrc file (e.g., set ai ). Used by vi and ex .

LOGNAME

Another name for the USER variable.

MAIL

The file that holds mail. Used by mail programs. This is not the same as the C shell mail variable, which only checks for new mail.

PWD

The current directory; the value is copied from cwd .

SHELL

Undefined by default; once initialized to shell , the two are identical.


Previous: 5.2 Syntax UNIX in a Nutshell: System V Edition Next: 5.4 Expressions
5.2 Syntax Book Index 5.4 Expressions

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System