5.4. Variables

 < Day Day Up > 

This subsection describes the following:

  • Variable substitution

  • Variable modifiers

  • Predefined shell variables

  • Formatting in the prompt variable

  • Sample .tcshrc file

  • Environment variables

5.4.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 considered part of the name.

Variable

Description

${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 also can be a variable that expands to one of these values.

${#var}

The number of words in var.

${#argv}

The number of arguments.

$#

Same as ${#argv}.

${%var}

The number of characters in var.

${%n}

The number of characters in $argv[n].

$0

Name of the program.

${argv[n]}

Individual arguments on command line (positional parameters); 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.

$?0

Return 1 if input filename is known, 0 if not.

$$

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

$?

Same as $status.

$!

Process ID number of last background process started by the shell.

$_

Text of the command line of the last command executed.

$<

Read a line from standard input.


5.4.1.1. Examples

Sort the third through last arguments and save the output in a file whose name is unique to this process:

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

In a .tcshrc file, process commands only if the shell is interactive (i.e., if the prompt variable is set):

     if ($?prompt) then         set commands,         alias commands,         etc.     endif

5.4.2. Variable Modifiers

Except for $?var, $?0, $#var, $%var, $#, $$, $?, $!, $_, and $<, the variable substitutions in the preceding section may be followed by one of these modifiers (when braces are used, the modifier goes inside them):

:r

Return the variable's root (the portion before the last dot).

:e

Return the variable's extension.

:h

Return the variable's header (the directory portion).

:t

Return the variable's tail (the portion after the last slash).

: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. Prevents further substitution. Useful when the variable contains filename metacharacters that should not be expanded.

:x

Quote a pattern, expanding it into a wordlist.


5.4.2.1. Examples using pathname modifiers

The following table shows the effect of pathname modifiers if the aa variable is set as follows:

     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.4.2.2. Examples using quoting modifiers

Unless quoted, the shell expands variables to represent files in the current directory:

     % 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.4.3. Predefined Shell Variables

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

     set var=value

or by simply turning the variable on:

     set var

The latter case is useful for simple "Is the variable set?" kinds of tests.

In the following list, 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, and status are never explicitly assigned.) For variables that are turned on or off, the list describes what they do when set. tcsh automatically sets (and, in some cases, updates) the variables addsuffix, argv, autologout, command, csubstnonl, cwd, dirstack, echo-style, edit, gid, home, loginsh, logout, owd, path, prompt, prompt2, prompt3, shell, shlvl, status, tcsh, term, tty, uid, user, and version.


addsuffix

Append / to directories and a space to files during tab completion to indicate a precise match.


afsuser

Set value to be used instead of the local username for Kerberos authentication with the autologout locking feature.


ampm

Display all times in 12-hour format.


argv=( args)

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


autocorrect

Check spelling before attempting to complete commands.


autoexpand

Expand history (such as ! references) during command completion.


autolist[=ambiguous]

Print possible completions when correct one is ambiguous. If ambiguous is specified, print possible completions only when completion adds no new characters.


autologout=( logout-minutes [ locking-minutes])

Log out after logout-minutes of idle time. Lock the terminal after locking-minutes of idle time, requiring a password before continuing. Not used if the DISPLAY environment variable is set.


backslash_quote

Always allow backslashes to quote \, ', and ".


catalog

Use tcsh.${catalog} as the filename of the message catalog. The default is tcsh.


cdpath=( dirs)

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


color

Turn on color for ls-F, ls, or both. Setting to nothing is equivalent to setting for both.


colorcat

Enable color escape sequence for Native Language System (NLS) support and display NLS messages in color.


command

If set, holds the command passed to the shell with the -c option.


complete=enhance

If set to enhance, ignore case in completion, treat ., -, and _ as word separators, and consider _ and - to be the same.


continue=( cmdlist)

cmdlist is a list of command names. If a stopped job consists of one of the named commands, restart that job when the user enters the corresponding command name, instead of starting a new job.


continue_args=( cmdlist)

Like continue, but execute the following:

     echo 'pwd' $argv > ~/.cmd_pause; %cmd


correct={cmd|complete|all}

When cmd, spellcheck commands. When complete, complete commands. When all, spellcheck whole command line.


csubstnonl

Newlines and carriage returns in command substitution output are replaced by spaces. Set by default.


cwd= dir

Full pathname of current directory.


dextract

When set, the pushd command extracts the desired directory and puts it at the top of the stack instead of rotating the stack.


dirsfile= file

History file consulted by dirs -S and dirs -L. Default is ~/.cshdirs.


dirstack

Directory stack, in array format. dirstack[1] is always equivalent to cwd. The other elements can be artificially changed.


dspmbyte= code

Enable use of multibyte code; for use with Kanji. See the tcsh manpage for details.


dunique

Make sure that each directory exists only once in the stack.


echo

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


echo_style={bsd|sysv|both|none}

Don't echo a newline with the -n option (bsd), parse escaped characters (sysv), do both, or do neither.


edit

Enable command-line editor. Set by default for interactive shells.


ellipsis

For use with prompt variable. Use ... to represent skipped directories.


fignore=( suffs)

List of filename suffixes to ignore during filename completion.


filec

This variable exists for compatibility with the 4.3 BSD csh. By default, it is ignored in tcsh. However, if edit has been unset, then if filec is 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 CTRL-D (EOF) to list possible completions.


gid

User's group ID.


group

User's group name.


histchars= ab

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


histdup={all|prev|erase}

Maintain a record only of unique history events (all), do not enter a new event when it is the same as the previous one (prev), or remove an old event that is the same as the new one (erase).


histfile= file

History file consulted by history -S and history -L. Default is ~/.history.


histlit

Do not expand history lines when recalling them.


history=( n format)

The first word indicates the number of commands to save in the history list. The second indicates the format with which to display that list. See the section "Formatting for the Prompt Variable" later in this chapter for possible formats.


home= dir

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


ignoreeof

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


implicitcd[=verbose]

If a directory name is entered as a command, cd to that directory. Can be set to verbose to echo the cd to standard output.


inputmode={insert|overwrite}

Control editor's mode.


killdup={all|prev|erase}

Enter only unique strings in the kill ring (all), do not enter a new string when it is the same as the current killed string (prev), or erase from the kill ring an old string that is the same as the current string (erase).


killring= num

Set the number of killed strings to keep in memory to num. The default is 30. If unset or set to a number less than two, keep only the most recently killed string.


listflags=( flags [ path])

One or more of the a, A, or x options for the ls-F built-in command. The second word can be set to the path for the ls command.


listjobs[=long]

When a job is suspended, list all jobs (in long format, if specified).


listlinks

In the ls-F command, include the type of file to which links point (directory, nonexistent file, nondirectory).


listmax= num

Do not allow the list-choices editor command to print more than num choices before prompting.


listmaxrows= num

Do not allow the list-choices editor command to print more than num rows of choices before prompting.


loginsh

Set if shell is a login shell.


logout

Indicates status of an imminent logout (normal, automatic, or hangup). Useful in a ~/.logout file.


mail=( n files)

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


matchbeep={never|nomatch|ambiguous|notunique}

Specifies circumstances under which completion should beep: never, if no match exists, if multiple matches exist, or if multiple matches exist and one is exact. If unset, ambiguous is used.


nobeep

Disable beeping, such as for ambiguous file completion.


noclobber

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


noding

Don't print DING! in prompt time specifiers when the hour changes.


noglob

Turn off filename expansion; useful in shell scripts.


nokanji

Disable Kanji (if supported).


nonomatch

Treat filename metacharacters as literal characters if no match exists (e.g., vi ch* creates new file ch* instead of printing "No match").


nostat=( directory-list)

Do not stat directory-list during completion.


notify

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


owd

Old working directory.


path=( dirs)

List of pathnames in which to search for commands to execute. Initialized from PATH; the default is . /usr/ucb /bin /usr/bin. However, standard start-up scripts may change it.


printexitvalue

Print all nonzero exit values.


prompt=' str'

String that prompts for interactive input; default is %# in interactive shells. See the section "Formatting for the Prompt Variable" later in this chapter for formatting information.


prompt2=' str'

String that prompts for interactive input in foreach and while loops and continued lines (those with escaped newlines). See the section "Formatting for the Prompt Variable" for formatting information.


prompt3=' str'

String that prompts for interactive input in automatic spelling correction. See the section "Formatting for the Prompt Variable" for formatting information.


promptchars= cc

Use the two characters specified as cc with the %# prompt sequence to indicate normal users and the superuser, respectively.


pushdsilent

Do not print directory stack when pushd and popd are invoked.


pushdtohome

Change to home directory when pushd is invoked without arguments.


recexact

Consider completion to be concluded on first exact match.


recognize_only_executables

When command completion is invoked, show only executable files.


rmstar

Prompt before executing the command rm *.


rprompt= string

The string to print on the right side of the screen while the prompt is displayed on the left. The string may have the same special contents as for the prompt variable.


savedirs

Execute dirs -S before exiting.


savehist=( max [merge])

Execute history -S before exiting. Save no more than max lines of history. If merge specified, merge those lines with previous history saves, and sort by time.


sched= string

Format for sched's printing of events. See the section "Formatting for the Prompt Variable" for formatting information.


shell= file

Pathname of the shell program.


shlvl

Number of nested shells.


status= n

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


symlinks={chase|ignore|expand}

Specify manner in which to deal with symbolic links. Expand them to real directory name in cwd (chase), treat them as real directories (ignore), or expand arguments that resemble pathnames (expand).


tcsh

Version of tcsh.


term

Terminal type.


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. See the tcsh manpage for the details.


tperiod

Number of minutes between executions of the periodic alias (described later in this chapter).


tty

Name of tty, if applicable.


uid

User ID.


user

Login name of user, initialized from USER.


verbose

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


version

Shell's version and additional information, including options set at compile time.


visiblebell

Flash screen instead of beeping.


watch=([ n] user terminal...)

Watch for user logging in at terminal, where terminal can be a device name or any. Check every n minutes, or 10 by default.


who= string

Specify information to be printed by watch. See the tcsh manpage for the details.


wordchars= chars

List of all nonalphanumeric characters that may be part of a word. Default is *?_-.[ ]~=.

5.4.4. Formatting for the Prompt Variable

tcsh provides a list of substitutions that can be used in formatting the prompt. The list of available substitutions includes:

%%

Literal %.

%/

The present working directory.

%~

The present working directory, in ~ notation.

%#

# for the superuser, > for others.

%?

Previous command's exit status.

%$var

The value of the shell or environment variable var.

%{string%}

Include string as a literal escape sequence to change terminal attributes (but should not move the cursor location); cannot be the last sequence in the prompt.

\c, ^c

Parse c as in the bindkey built-in command.

%b

End boldfacing.

%B

Begin boldfacing.

%c[[0]n], %.[[0]n]

The last n (default 1) components of the present working directory; if a leading 0 is specified, replace removed components with /<skipped>.

%C

Similar to %c, but use full pathnames instead of ~ notation.

%d

Day of the week (e.g., Mon, Tue).

%D

Day of month (e.g., 09, 10).

%h, %!, !

Number of current history event.

%j

The number of jobs.

%l

Current tty.

%L

Clear from the end of the prompt to the end of the display or the line.

%m

First component of hostname.

%M

Fully qualified hostname.

%n

Username.

%p

Current time, with seconds (12-hour mode).

%P

Current time, with seconds (24-hour format).

%R

In prompt2, the parser status; in prompt3, the corrected string; and in history, the history string.

%s

End standout mode (reverse video).

%S

Begin standout mode (reverse video).

%t, %@

Current time (12-hour format).

%T

Current time (24-hour format).

%u

End underlining.

%U

Begin underlining.

%w

Month name (e.g., Jan, Feb).

%W

Month number (e.g., 09, 10).

%y

Year, two digits (e.g., 06, 07).

%Y

Year, four digits (e.g., 2006, 2007).


5.4.5. Sample .tcshrc 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 noclobber ignoreeof       set cdpath=(/usr/lib /var/spool/uucp)     # Now I can type cd macros     # instead of cd /usr/lib/macros       set history=100       set prompt='tom \!% '              # includes history number       set time=3     # MY VARIABLES       set man1="/usr/share/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.4.6. Environment Variables

tcsh maintains a set of environment variables , which are distinct from shell variables and aren't really part of the shell. Shell variables are meaningful only within the currently running shell, but environment variables are exported automatically, making them available to other programs run by the shell. For example , shell variables are accessible only to the 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 predefined environment variables that follow.

The following environment variables have corresponding tcsh shell variables. When either one changes, the value is copied to the other.

AFSUSER

Alternative to local user for Kerberos authentication with autologout locking; same as afsuser.

GROUP

User's group name; same as group.

HOME

Home directory; same as home.

PATH

Search path for commands; same as path.

SHLVL

Number of nested shell levels; same as shlvl.

TERM

Terminal type; same as term.

USER

User's login name; same as user.


Other environment variables, which do not have corresponding shell variables, include the following:

COLUMNS

Number of columns on terminal.

DISPLAY

Identifies user's display for the X Window System. If set, the shell doesn't set autologout.

EDITOR

Pathname to default editor. See also VISUAL.

EXINIT

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

HOST

Name of machine.

HOSTTYPE

Type of machine. Obsolete; will be removed eventually.

HPATH

Colon-separated list of directories to search for documentation for the run-help editor command.

LANG

Preferred language. Used for native language support.

LC_CTYPE

The locale, as it affects character handling. Used for native language support.

LINES

Number of lines on the screen.

LOGNAME

Another name for the USER variable.

LS_COLORS

Colors for use with the ls command. See the tcsh manpage for detailed information.

MACHTYPE

Type of machine.

MAIL

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

NOREBIND

Printable characters not rebound. Used for native language support.

OSTYPE

Operating system.

PWD

The current directory; the value is copied from cwd, but only after a directory change.

REMOTEHOST

Machine name of remote host from which the user logged in.

SHELL

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

TERMCAP

The file that holds the cursor-positioning codes for your terminal type. Default is /etc/termcap.

VENDOR

System vendor.

VISUAL

Pathname to default full-screen editor. See also EDITOR.


     < Day Day Up > 


    Unix in a Nutshell
    Unix in a Nutshell, Fourth Edition
    ISBN: 0596100299
    EAN: 2147483647
    Year: 2005
    Pages: 201

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net