Previous Section  < Day Day Up >  Next Section

9.10. Variables

C/TC shell variables hold only strings or a set of strings. Some variables are built into the shell and can be set by turning them on or off, such as the noclobber or filec variable. Others are assigned a string value, such as the path variable. You can create your own variables and assign them to strings or the output of commands. Variable names are case sensitive and may contain up to 20 characters consisting of numbers, letters, and the underscore.

There are two types of variables: local and environment. Local variables are created with the set command. Global variables are created with the setenv command. The scope of a variable is its visibility. A local variable is visible to the shell where it is defined. The scope of environment variables is often called global. Their scope is for this shell and all processes spawned (started) from this shell.

The dollar sign ($) is a special metacharacter that, when preceding a variable name, tells the shell to extract the value of that variable. The echo command, when given the variable as an argument, will display the value of the variable after the shell has processed the command line and performed variable substitution.

The special notation $?, when prepended to the variable name, lets you know whether the variable has been set. If a one is returned, it means true, the variable has been set. If a zero is returned, it means false, the variable has not been set.

Example 9.46.

1   % set filec

2   % set history = 50

3   % set name = George

4   % set machine = `uname -n`

5   % echo  $?machine

    1

6   % echo  $?blah

    0


EXPLANATION

  1. Sets the built-in variable filec for filename completion. It is either on or off.

  2. Sets the built-in variable history to 50 to control the number of events displayed.

  3. Sets the user-defined variable name to George.

  4. Sets the user-defined variable machine to the output of the UNIX command. The command is in backquotes, telling the shell to perform command substitution.

  5. Because $? is prepended to the variable name to test whether the variable has been set. Since the test yields a 1 (true), the variable has been set.

  6. The $? yields 0 (false). The variable has not been set.

9.10.1 Curly Braces

Curly braces insulate a variable from any characters that may follow it.

Example 9.47.

1   % set var = net

    % echo $var

    net

2   % echo $varwork

    varwork: Undefined variable.

3   % echo ${var}work

    network


EXPLANATION

  1. The curly braces surrounding the variable name insulate the variable from characters that follow it.

  2. A variable called varwork has not been defined. The shell prints an error message.

  3. The curly braces shield the variable from characters appended to it. $var is expanded and the string work is appended.

9.10.2 Local Variables

Local variables are known only in the shell where they were created. If a local variable is set in the .cshrc file, the variable will be reset every time a new C shell is started. By convention, local variables are named with lowercase letters.

Setting Local Variables

If the string being assigned contains more than one word, it must be quoted; otherwise, only the first word will be assigned to the variable. It does not matter if there are spaces around the equal sign, but if there is a space on one side of the equal sign, there must be one on the other side.

Example 9.48.

1   % set round = world

2   % set name = "Santa Claus"

3   % echo $round

     world

4   % echo $name

    Santa Claus

5   % csh                # Start a subshell

6   % echo $name

    name: Undefined variable.


EXPLANATION

  1. The local variable round is assigned the value world.

  2. The local variable name is assigned the value Santa Claus. The double quotes keep the shell from evaluating the whitespace between Santa and Claus.

  3. The dollar sign prepended to the variable allows the shell to perform variable substitution, that is, to extract the value stored in the variable.

  4. Variable substitution is performed.

  5. A new C shell (called a subshell) process is started.

  6. In the subshell, the variable name has not been defined. It was defined in the parent shell as a local variable.

The set Command

The set command prints all local variables set for this shell.

Example 9.49.

(The Command Line--Linux/tcsh)

> set

addsuffix

argv          ()

cwd           /home/jody/meta

dirstack      /home/ellie/meta

echo_style both

edit

gid       501

group     ellie

history   500

home     /home/ellie

i        /etc/profile.d/mc.csh

owd      /home/ellie

noclobber

path  (/usr/sbin /sbin /usr/local/bin /bin  /usr/bin /usr/X11R6/bin )

prompt    [%n@%m  %c]#

prompt2   %R?

prompt3   CORRECT>%R  (y|n|e|a)?

savedirs

shell     /bin/tcsh

shlvl     2

status    0

tcsh      6.07.09

term      xterm

user      ellie

version tcsh 6.07.09 (Astron) 2004-07-07 (i386-intel-linux)

options 8b,nls,dl,al,rh,color


EXPLANATION

All of the local variables set for this shell are printed. Many of these variables, such as history , dirstack, and noclobber, are set in the .tcshrc file. Others, such as argv , cwd, shell, term, user, version, and status variables are preset, built-in variables.

Example 9.50.

(The Command Line--UNIX/csh)

% set

argv          ()

cwd           /home/jody/ellie

fignore       .o

filec

history       500

home          /home/jody/ellie

hostname      jody

ignoreeof

noclobber

notify

path          (/home/jody/ellie /bin /usr/local /usr/usr/bin/usr/etc .)

prompt        jody%

shell         /bin/csh

status        0

term          sun–cmd

user          ellie


EXPLANATION

All of the local variables set for this shell are printed. Most of these variables are set in the .cshrc file. The argv , cwd, shell, term, user, and status variables are preset, built-in variables.

Read-Only Variables (tcsh)

Read-only variables are local variables that, once set, cannot be changed or unset or an error message will result. Environment variables cannot be made read-only. If using the C shell, the following example will cause the error: set: Syntax error.

Example 9.51.

1   > set -r name = Tommy

2   > unset name

    unset: $name is read-only.

3   > set name = Danny

    set: $name is read-only


Built-In Local Variables

The shell has a number of predefined variables with their own definitions. Some of the variables are either on or off. For example, if you set noclobber, the variable is on and effective, and when you unset noclobber, it is turned off. Some variables require a definition when set. Built-in variables are usually set in the .cshrc file for the C shell and the .tschrc file for the TC shell if they are to be effective for different C/TC shells. Some of the built-in variables already discussed include noclobber, cdpath, history , filec, and noglob. For a complete list, see Table 9.26 on page 514.

Table 9.26. Special C/TC Shell Variables[a] [b]

Variable

Meaning

addsufix (+)

For filename completion, adds slashes at the end of directories and space to the end of normal files if they are matched. Set by default.

afsuser (+)

If set, autologout's autolock feature uses its value instead of the local username for Kerberos authentication.

ampm (+)

If set, all times are shown in 12-hour AM/PM format.

argv

An array of command-line arguments to the shell; also represented as $1, $2, and so on.

autocorrect (+)

Invokes the spell checker before each attempt at filename, command, or variable completion.

autoexpand (+)

If set, the expand-history editor command is invoked automatically before each completion attempt.

autolist (+)

If set, possibilities are listed after an ambiguous completion. If set to ambiguous, possibilities are listed only when no new characters are added by completion.

autologout (+)

Its argument is the number of minutes of inactivity before automatic logout; the second optional argument is the number of minutes before automatic locking causes the screen to lock.

backslash_quote (+)

If set, a backslash will always quote itself, a single quote or a double quote.

cdpath

A list of directories in which cd should search for subdirectories if they aren't found in the current directory.

color (+)

Enables color display for the built-in command ls-F and passes --color=auto to ls.

complete (+)

If set to enhance, completion ignores case, considers periods, hyphens, and underscores to be word separators, and hyphens and underscores to be equivalent.

correct (+)

If set to cmd, commands are automatically spelling-corrected. If set to complete, commands are automatically completed. If set to all, the entire command line is corrected.

cwd

The full pathname of the current working directory.

dextract (+)

If set, pushd +n extracts the nth directory from the directory stack rather than rotating it to the top.

dirsfile (+)

The default location in which dirs -S and dirs -L look for a history file. If unset, ~/.cshdirs is used.

dirstack (+)

A list of all directories on the directory stack.

dunique (+)

Will not allow pushd to keep duplicate directory entries on the stack.

echo

If set, each command with its arguments is echoed just before it is executed. Set by the -x command-line option.

echo-style (+)

Sets the style for echo. If set to bsd will not echo a newline if the first argument is -n; if set to sysv, recognizes backslashed escape sequences in echo strings; if set to both, recognizes both the -n flag and backslashed escape sequences; the default, and if set to none, recognizes neither.

edit (+)

Sets the command-line editor for interactive shells; set by default.

ellipsis (+)

If set, the %c, %., and %C prompt sequences (see the "The Shell Prompts" on page 461) indicate skipped directories with an ellipsis (...) instead of /<skipped>.

fignore

Lists filename suffixes to be ignored by completion.

filec (+)

In tcsh, completion is always used and this variable is ignored. If set in csh, filename completion is used.

gid (+)

The user's read group ID number.

group (+)

The user's group name.

hardpaths

If set, pathnames in the directory stack are resolved to contain no symbolic-link components.

histchars

A string value determining the characters used in history substitution. The first character of its value is used as the history substitution character to replace the default character, !. The second character of its value replaces the character ^ in quick substitutions.

histdup (+)

Controls handling of duplicate entries in the history list. Can be set to all (removes all duplicates), prev (removes the current command if it duplicates the previous command), or erase (inserts the current event for an older duplicate event).

histfile (+)

The default location in which history -S and history -L look for a history file. If unset, ~/.history is used.

histlit (+)

Enters events on the history list literally; that is, unexpanded by history substitution.

history

The first word indicates the number of history events to save. The optional second word (+) indicates the format in which history is printed.

home

The home directory of the user; same as ~.

ignoreeof

If logging out by pressing Ctrl-D, prints Use "exit" to leave tcsh. Prevents inadvertently logging out.

implicitcd (+)

If set, the shell treats a directory name typed as a command as though it were a request to change to that directory and changes to it.

inputmode (+)

If set to insert or overwrite, puts the editor into that input mode at the beginning of each line.

listflags (+)

If set to x, a, or A, or any combination (e.g., xA), values are used as flags to ls-F , making it act like ls -xF , ls -Fa, ls -FA, or any combination of those flags.

listjobs (+)

If set, all jobs are listed when a job is suspended. If set to long, the listing is in long format.

listlinks (+)

If set, the ls -F built-in command shows the type of file to which each symbolic link points.

listmax (+)

The maximum number of items the list-choices editor command will list without asking first.

listmaxrows (+)

The maximum number of rows of items the list-choices editor command will list without asking first.

loginsh (+)

Set by the shell if it is a login shell. Setting or unsetting it within a shell has no effect. See also shlvl.

logout (+)

Set by the shell to normal before a normal logout, automatic before an automatic logout, and hangup if the shell was killed by a hangup signal.

mail

The names of the files or directories to check for incoming mail. After 10 minutes if new mail has come in, will print You have new mail.

matchbeep (+)

If set to never, completion never beeps; if set to nomatch, completion beeps only when there is no match; and when set to ambiguous, beeps when there are multiple matches.

nobeep

Disables all beeping.

noclobber

Safeguards against the accidental removal of existing files when redirection is used; for example, ls > file.

noglob

If set, inhibits filename and directory stack substitutions when using wildcards.

nokanji (+)

If set and the shell supports Kanji (see the version shell variable), it is disabled so that the Meta key can be used.

nonomatch

If set, a filename substitution or directory stack substitution that does not match any existing files is left untouched rather than causing an error.

nostat (+)

A list of directories (or glob patterns that match directories) that should not be stat(2)ed during a completion operation. This is usually used to exclude directories that take too much time to stat(2).

notify

If set, the shell announces job completions asynchronously instead of waiting until just before the prompt appears.

oid (+)

The user's real organization ID. (Domain/OS only)

owd (+)

The old or previous working directory.

path

A list of directories in which to look for executable commands. path is set by the shell at startup from the PATH environment variable or, if PATH does not exist, to a system-dependent default, something like /usr/local/bin /usr/bsd /bin /usr/bin.

printexitvalue (+)

If set and an interactive program exits with a nonzero status, the shell prints Exit status.

prompt

The string that is printed before reading each command from the terminal; may include special formatting sequences (see "The Shell Prompts" on page 461).

prompt2 (+)

The string with which to prompt in while and foreach loops and after lines ending in \. The same format sequences may be used as in prompt; note the variable meaning of %R. Set by default to %R? in interactive shells.

prompt3 (+)

The string with which to prompt when confirming automatic spelling correction. The same format sequences may be used as in prompt; note the variable meaning of %R. Set by default to CORRECT>%R (y|n|e|a)? in interactive shells.

promptchars (+)

If set (to a two-character string), the %# formatting sequence in the prompt shell variable is replaced with the first character for normal users and the second character for the superuser.

pushtohome (+)

If set, pushd without arguments does pushd ~, like cd.

pushdsilent (+)

If set, pushd and popd to not print the directory stack.

recexact (+)

If set, completion completes on an exact match even if a longer match is possible.

recognize_only_ executables (+)

If set, command listing displays only files in the path that are executable.

rmstar (+)

If set, the user is prompted before rm * is executed.

rprompt (+)

The string to print on the right-hand side of the screen (after the command input) when the prompt is being displayed on the left. It recognizes the same formatting characters as prompt. It will automatically disappear and reappear as necessary, to ensure that command input isn't obscured, and will only appear if the prompt, command input, and itself will fit together on the first line. If edit isn't set, then rprompt will be printed after the prompt and before the command input.

savedirs (+)

If set, the shell does dirs -S before exiting.

savehist

If set, the shell does history -S before exiting. If the first word is set to a number, at most that many lines are saved. (The number must be less than or equal to history.) If the second word is set to merge, the history list is merged with the existing history file instead of replacing it (if there is one) and sorted by timestamp and the most recent events are retained.

sched (+)

The format in which the sched built-in command prints scheduled events; if not given, %h\t%T\t%R\n is used. The format sequences are described above under prompt; note the variable meaning of %R.

shell

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

shlvl (+)

The number of nested shells. Reset to 1 in login shells. See also loginsh.

status

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

symlinks (+)

Can be set to several different values to control symbolic link (symlink) resolution. (See tcsh man page for examples.)

tcsh (+)

The version number of the shell in the format R.VV.PP , where R is the major release number, VV the current version, and PP the patch level.

term (+)

The terminal type. Usually set in ~/.login as described under "C/TC Shell Startup" on page 403.

time

If set to a number, then the time built-in executes automatically after each command that takes more than that many CPU seconds. If there is a second word, it is used as a format string for the output of the time built-in. The following sequences may be used in the format string:

%c

The number of involuntary context switches.

%D

The average amount in (unshared) data/stack space used in KB.

%E

The elapsed (wall clock) time in seconds.

%F

The number of major page faults (page needed to be brought from disk).

%I

The number of input operations.

%K

The total space used (%X + %D) in KB.

%k

The number of signals received.

%M

The maximum memory the process had in use at any time in KB.

%O

The number of output operations.

%P

The CPU percentage computed as (%U + %S) / %E.

%R (+)

The number of minor page faults.

%r

The number of socket messages received.

%S

The time the process spent in kernel mode in CPU seconds.

%s

The number of socket messages sent.

%U

The time the process spent in user mode in CPU seconds.

%W

Number of times the process was swapped.

%w

The number of voluntary context switches (waits).

%X

The average amount in (shared) text space used in KB.

Only the %U, %S, %F , and %P sequences are supported on systems without BSD resource limit functions. The default time format is %Uu %Ss %E %P %X+%Dk %I+%Oio %Fpf+%Ww for systems that support resource usage reporting and %Uu %Ss %E %P for systems that do not.

Under Sequent's DYNIX/ptx, %X, %D, %K, %r, and %s are not available, but the following additional sequences are:

%Y

The number of system calls performed.

%Z

The number of pages that are zero-filled on demand.

%i

The number of times a process's resident set size was increased by the kernel.

%d

The number of times a process's resident set size was decreased by the kernel.

%l

The number of read system calls performed.

%m

The number of write system calls performed.

%p

The number of reads from raw disk devices.

%q

The number of writes to raw disk devices.

The default time format is %Uu %Ss $E %P %I+%Oio %Fpf+%Ww. Note that the CPU percentage can be higher than 100 percent on multiprocessors.

tperiod (+)

The period, in minutes, between executions of the periodic special alias.

tty (+)

The name of the tty , or empty if not attached to one.

uid (+)

The user's real user ID.

user (+)

The user's login name.

verbose

If set, causes the words of each command to be printed, after history substitution (if any). Set by the -v command-line option.

version (+)

The version ID stamp. It contains the shell's version number (see tcsh), origin, release date, vendor, operating system, and so forth.


[a] Variables with a (+) are TC shell only. All others are built in for both TC and C shells.

[b] Descriptions taken from tcsh manual pages.

9.10.3 Environment Variables

Environment variables are often called global variables. They are defined in the shell where they were created and inherited by all shells spawned from that shell. Although environment variables are inherited by subshells, those defined in subshells are not passed back to parent shells. Inheritance is from parent to child, not the other way around (like real life). By convention, environment variables are named with uppercase letters.

Example 9.52.

(The Command Line)

1   % setenv TERM wyse

2   % setenv PERSON "Joe Jr."

3   % echo $TERM

    wyse

4   % echo $PERSON

    Joe Jr.

5   % echo $$        # $$ evaluates to the PID of the current shell

    206

6   % csh            # Start a subshell

7   % echo $$

    211

8   % echo $PERSON

    Joe Jr.

9   % setenv PERSON "Nelly Nerd"

10  % echo $PERSON

    % Nelly Nerd

11  % exit             # Exit the subshell

12  % echo $$

    206

13  % echo $PERSON      # Back in parent shell

    Joe Jr.


EXPLANATION

  1. The shell environment variable TERM is set to a wyse terminal.

  2. The user-defined variable PERSON is set to Joe Jr.. The quotes are used to protect the space.

  3. The dollar sign ($) prepended to the variable name allows the shell to evaluate the contents of the variable, called variable substitution.

  4. The value of the environment variable PERSON is printed.

  5. The $$ variable contains the PID of the current shell. The PID is 206.

  6. The csh command starts a new C shell, called a subshell.

  7. The PID of the current shell is printed. Because this is a new C shell, it has a different PID number. The PID is 211.

  8. The environment variable PERSON was inherited by the new shell.

  9. The PERSON variable is reset to Nelly Nerd. This variable will be inherited by any shells spawned from this shell.

  10. The new value of the PERSON variable is printed.

  11. This C shell is exited.

  12. The original C shell is running; to attest to that, the PID 206 is printed. It is the same as it was before the subshell was started.

  13. The PERSON variable contains its original value.

Printing Environment Variables

The printenv (BSD) and env (SVR4) commands (both work in Linux) print all the environment variables set for this shell and its subshells. The setenv command prints variables and their values on both the BSD and SVR4 versions of the C shell.

Example 9.53.

(Linux/tcsh Example)



> env  or  printenv  or  setenv

USERNAME=root

COLORTERM=rxvt-xpm

HISTSIZE=1000

HOSTNAME=homebound

LOGNAME=ellie

HISTFILESIZE=1000

MAIL=/var/spool/mail/ellie

MACHTYPE=i386

COLORFGBG=0;default;15

TERM=xterm

HOSTTYPE=i386-linux

PATH=/usr/sbin:/sbin:/usr/local/bin:/bin:/usr/bin:/usr/

X11R6/bin:/home/ellie/bin;/root/bash-2.03/:/usr/X11R6/bin:/home/

ellie/bin;/root/bash-2.03/:/usr/X11R6/bin

HOME=/root

SHELL=/bin/bash

PS1=[\u@\h \W]\$

USER=ellie

VENDOR=intel

GROUP=ellie

HOSTDISPLAY=homebound:0.0

DISPLAY=:0.0

HOST=homebound

OSTYPE=linux

WINDOWID=37748738

PWD=/home/ellie

SHLVL=6

_=/usr/bin/env


EXPLANATION

The environment variables are set for this session and all processes that are started from this shell are displayed by using either one of the built-in commands: env or printenv. Many applications require the setting of environment variables. For example, the mail command has a MAIL variable set to the location of the user's mail spooler and the xterm program has a DISPLAY variable that determines which bit map display terminal to use. When any of these programs are executed, the values in their respective variables are passed on to them.

Example 9.54.

(UNIX/Solaris/csh Example)



% env

FONTPATH=/usr/local/OW3/lib/fonts

HELPPATH=/usr/local/OW3/lib/locale:/usr/local/OW3/lib/help

HOME=/home/jody/ellie

LD_LIBRARY_PATH=/usr/local/OW3/lib

LOGNAME=ellie

MANPATH=/ur/local/man:/usr/local/man:/usr/local/doctools/man:/usr/man

NOSUNVIEW=0

OPENWINHOME=/usr/local/OW3

PATH=/bin:/usr/local:/usr:/usr/bin:/usr/etc:/home/5bin:/usr/

   doctools:/usr:.

PWD=/home/jody/ellie

SHELL=/bin/csh

TERM=sun–cmd

USER=ellie

WINDOW_PARENT=/dev/win0

WINDOW_TTYPARMS=

WMGR_ENV_PLACEHOLDER=/dev/win3


9.10.4 Arrays

In the C shell, an array is simply a list of words, separated by spaces or tabs, and enclosed in parentheses. The elements of the array are numbered by subscripts starting at 1. If there is not an array element for a subscript, the message Subscript out of range is displayed. Command substitution will also create an array. If the $# notation precedes an array name, the number of elements in the array is displayed.

Example 9.55.

1   % set fruit = ( apples pears peaches plums )

2   % echo $fruit

    apples pears peaches plums

3   % echo $fruit[1]        # Subscripts start at 1

    apples

4   % echo $fruit[2–4]      # Prints the 2nd, 3rd, and 4th elements

    pears peaches plums

5   $ echo $fruit[6]

    Subscript out of range.

6   % echo $fruit[*]         # Prints all elements of the array

    apples pears peaches plums

7   % echo $#fruit           # Prints the number of elements

    4

8   % echo $fruit[$#fruit]   # Prints the last element

    plums

9   % set fruit[2] = bananas # Reassigns the second element

    % echo $fruit

    apples bananas peaches plums

10  % set path = ( ~ /usr/bin /usr /usr/local/bin . )

    % echo $path

    /home/jody/ellie /usr/bin /usr /usr/local/bin .

11   % echo $path[1]

    /home/jody/ellie


EXPLANATION

  1. The wordlist is enclosed within parentheses. Each word is separated by whitespace. The array is called fruit.

  2. The words in the fruit array are printed.

  3. The first element of the fruit array is printed. The subscripts start at 1.

  4. The second, third, and fourth elements of the wordlist are printed. The dash allows you to specify a range.

  5. The array does not have six elements. The subscript is out of range.

  6. All elements of the fruit array are printed.

  7. The $# preceding the array is used to obtain the number of elements in the array. There are four elements in the fruit array.

  8. Because the subscript $#fruit evaluates to the total number of elements in the array, if that value is used as an index value of the array, that is, [$#fruit], the last element of the fruit array is printed.

  9. The second element of the array is assigned a new value. The array is printed with its replaced value, bananas.

  10. The path variable is a special C shell array of directories used to search for commands. By creating an array, the individual elements of the path can be accessed or changed.

  11. The first element of path is printed.

The shift Command and Arrays

If the built-in shift command takes an array name as its argument, it shifts off (to the left) the first element of the array. The length of the array is decreased by one. (Without an argument, the shift command shifts off the first element of the built-in argv array. See "Command-Line Arguments" on page 534.)

Example 9.56.

1   % set names = ( Mark Tom Liz Dan Jody )

2   % echo $names

    Mark Tom Liz Dan Jody

3   % echo $names[1]

    Mark

4   % shift  names

5   % echo $names

    Tom Liz Dan Jody

6   % echo $names[1]

    Tom

7   % set days = ( Monday Tuesday )

8   % shift days

9   % echo $days

    Tuesday

10  % shift days

11  % echo $days

12  % shift days

    shift: no more words.


EXPLANATION

  1. The array is called names. It is assigned the list of words in parentheses. Each word is separated by whitespace.

  2. The array is printed.

  3. The first element of the array is printed.

  4. The array is shifted to the left by one element. The word Mark is shifted off.

  5. The array was decreased by one element after the shift.

  6. The first element of the array, after the shift, is Tom.

  7. An array called days is created. It has two elements, Monday and Tuesday.

  8. The array days is shifted one to the left.

  9. The array is printed. Tuesday is the only element left.

  10. The array days is shifted again. The array is empty.

  11. The days array is empty.

  12. This time, attempting to shift causes the shell to send an error message indicating that it cannot shift elements from an empty array.

Creating an Array from a String

You may want to create a wordlist out of a quoted string. This is accomplished by placing the string variable within a set of parentheses.

Example 9.57.

1   % set name = "Thomas Ben Savage"

    % echo $name[1]

    Thomas Ben Savage

2   % echo $name[2]

    Subscript out of range.

3   % set name = ( $name )

4   % echo $name[1] $name[2] $name[3]

    Thomas Ben Savage


EXPLANATION

  1. The variable name is assigned the string Thomas Ben Savage.

  2. When treated as an array, there is only one element, the entire string.

  3. The variable is enclosed in parentheses, creating an array of words, called name.

  4. The three elements of the new array are displayed.

9.10.5 Special Variables

Built into the C shell are several variables consisting of one character. The $ preceding the character allows variable interpretation. See Table 9.7.

Table 9.7. Variables and Their Meanings

Variable

Example

Meaning

$?var

echo $?name

Returns 1 if variable has been set, 0 if not.

$#var

echo $#fruit

Prints the number of elements in an array.

$$

echo $$

Prints the PID of the current shell.

$<

set name = $<

Accepts a line of input from user up to newline.


Example 9.58.

1   % set num

    % echo $?num

    1

2   % echo $path

    /home/jody/ellie   /usr/bin/   usr/local/bin

    % echo $#path

    3

3   % echo $$

    245

    % csh              # Start a subshell

    % echo $$

    248

4   % set name = $<

    Christy Campbell

    % echo $name

    Christy Campbell


EXPLANATION

  1. The variable num is set to null. The $? preceding the variable evaluates to one if the variable has been set (either to null or some value), and to zero if the variable has not been set.

  2. The path variable is printed. It is an array of three elements. The $# preceding the variable extracts and prints the number of elements in the array.

  3. The $$ is the PID of the current process, in this case, the C shell.

  4. The $< variable accepts a line of input from the user up to, but not including, the newline, and stores the line in the name variable. The value of the name variable is displayed.

Pathname Variable Modifiers

If a pathname is assigned to a variable, it is possible to manipulate the pathname variable by appending special C shell extensions to it. The pathname is divided into four parts: head, tail, root, and extension. See Table 9.8 for examples of pathname modifiers and what they do.

Table 9.8. Pathname Modifiers set pn = /home/ellie/prog/check.c

Modifier

Meaning

Example

Result

:r

Root

echo $pn:r

/home/ellie/prog/check

:h

Head

echo $pn:h

/home/ellie/prog

:t

Tail

echo $pn:t

check.c

:e

Extension

echo $pn:e

c

:g

Global

echo $p:gt

(See Example 9.59)


Example 9.59.

1   % set pathvar = /home/danny/program.c

2   % echo $pathvar:r

    /home/danny/program

3   % echo $pathvar:h

    /home/danny

4   % echo $pathvar:t

    program.c

5   % echo $pathvar:e

    c

6   % set pathvar = ( /home/* )

    echo $pathvar

    /home/jody /home/local /home/lost+found /home/perl /home/tmp

7   % echo $pathvar:gt

    jody  local  lost+found  perl tmp


EXPLANATION

  1. The variable pathvar is set to /home/danny/program.c.

  2. When :r is appended to the variable, the extension is removed when displayed.

  3. When :h is appended to the variable, the head of the path is displayed; that is, the last element of the path is removed.

  4. When :t is appended to the variable, the tail end of the path (the last element) is displayed.

  5. When :e is appended to the variable, the extension is displayed.

  6. The variable is set to /home/*. The asterisk expands to all the pathnames in the current directory starting in /home/.

  7. When :gt is appended to the variable, the tail end of each (global) of the path elements is displayed.

    Previous Section  < Day Day Up >  Next Section