Although tcsh stores variable values as strings, you can work with these variables as numbers. Expressions in tcsh can use arithmetic, logical, and conditional operators. The @ builtin can evaluate integer arithmetic expressions. This section uses the term numeric variable to describe a string variable that contains a number that tcsh uses in arithmetic or logical arithmetic computations. However, no true numeric variables exist in tcsh. Variable name A tcsh variable name consists of 1 to 20 characters, which can be letters, digits, and underscores (_). The first character cannot be a digit but can be an underscore. Variable SubstitutionThree builtins declare, display, and assign values to variables: set, @, and setenv. The set and setenv builtins both assume nonnumeric string variables. The @ builtin works only with numeric variables. Both set and @ declare local variables. The setenv builtin declares a variable and places it in the calling environment of all child processes (makes it global). Using setenv is similar to assigning a value to a variable and then using export in the Bourne Again Shell. See "Locality of Variables" on page 560 for a discussion of local and environment variables. Once the valueor merely the existenceof a variable has been established, tcsh substitutes the value of that variable when the name of the variable, preceded by a dollar sign ($), appears on a command line. If you quote the dollar sign by preceding it with a backslash or enclosing it within single quotation marks, the shell does not perform the substitution. When a variable is within double quotation marks, the substitution occurs even if you quote the dollar sign by preceding it with a backslash. String VariablesThe TC Shell treats string variables similarly to the way the Bourne Again Shell does. The major difference is in their declaration and assignment: tcsh uses an explicit command, set (or setenv), to declare and/or assign a value to a string variable. tcsh $ set name = fred tcsh $ echo $name fred tcsh $ set argv () cwd /Users/alex home /Users/alex name fred path (/bin /sbin /usr/bin /usr/sbin) prompt $ shell /bin/tcsh status 0 term vt100 user alex The first line in the example declares the variable name and assigns the string fred to it. Unlike bash, tcsh allows but does not demand SPACEs around the equal sign. The next line displays this value. When you give a set command without any arguments, it displays a list of all local shell variables and their values (your list will be longer than the one in the example). When you give a set command with the name of a variable and no value, the command sets the value of the variable to a null string. You can use the unset builtin to remove a variable: tcsh $ set name tcsh $ echo $name tcsh $ unset name tcsh $ echo $name name: Undefined variable. With setenv you must separate the variable name from the string being assigned to it by one or more SPACEs and no equal sign. The tcsh command creates a subshell, echo shows that the variable and its value are known to the subshell, and exit returns to the original shell. Try this example, using set in place of setenv: tcsh $ setenv SCRDIR /usr/local/src tcsh $ tcsh tcsh $ echo $SCRDIR /usr/local/src tcsh $ exit If you use setenv with no arguments, it displays a list of the environment (global) variablesvariables that are passed to the shell's child processes. By convention, environment variables are named using uppercase letters. As with set, giving setenv a variable name without a value sets the value of the variable to a null string. Although you can use unset to remove environment and local variables, unsetenv can remove only environment variables. Arrays of String VariablesAn array is a collection of strings, each of which is identified by its index (1, 2, 3, and so on). Arrays in tcsh use one-based indexing (the first element of the array has the subscript 1). Before you can access individual elements of an array, you must declare the entire array by assigning a value to each element of the array. The list of values must be enclosed in parentheses and separated by SPACEs: 8 $ set colors = (red green blue orange yellow) 9 $ echo $colors red green blue orange yellow 10 $ echo $colors[3] blue 11 $ echo $colors[2-4] green blue orange 12 $ set shapes = ('' '' '' '' '') 13 $ echo $shapes 14 $ set shapes[4] = square 15 $ echo $shapes[4] square Event 8 declares the array of string variables named colors to have five elements and assigns values to each of them. If you do not know the values of the elements at the time you declare an array, you can declare an array containing the necessary number of null elements (event 12). You can reference an entire array by preceding its name with a dollar sign (event 9). A number in brackets following a reference to the array refers to an element of the array (events 10, 14, and 15). Two numbers in brackets, separated by a hyphen, refer to two or more adjacent elements of the array (event 11). Refer to "Special Variable Forms" on page 357 for more information on arrays. Numeric VariablesThe @ builtin assigns the result of a numeric calculation to a numeric variable (as described under "Variables" [page 352], tcsh has no true numeric variables). You can declare single numeric variables with @, just as you can use set to declare nonnumeric variables. However, if you give it a nonnumeric argument, @ displays an error message. Just as set does, the @ command used without any arguments lists all shell variables. Many of the expressions that the @ builtin can evaluate and the operators it recognizes are derived from the C programming language. The following format shows a declaration or assignment using @ (the SPACE after the @ is required): @ variable-name operator expression The variable-name is the name of the variable that you are assigning a value to. The operator is one of the C assignment operators: =, +=, =, *=, /=, or %=. (See page 614 for an explanation of these operators.) The expression is an arithmetic expression that can include most C operators (see the next section). You can use parentheses within the expression for clarity or to change the order of evaluation. Parentheses must surround parts of the expression that contain any of the following characters: <, >, &, or |. Tip: Do not use $ when assigning a value to a variable As with bash, variables having a value assigned to them (those on the left of the operator) must not be preceded by a dollar sign ($). Thus tcsh $ @ $answer = 5 + 5 will yield answer: Undefined variable. or, if answer is defined, @: Variable name must begin with a letter. whereas tcsh $ @ answer = 5 + 5 assigns the value 10 to the variable answer. ExpressionsAn expression is composed of constants, variables, and most any of the bash operators (page 588). Expressions that involve files rather than numeric variables or strings are described in Table 9-8 on page 365. Expressions follow these rules:
Following are some examples that use @: 216 $ @ count = 0 217 $ echo $count 0 218 $ @ count = ( 10 + 4 ) / 2 219 $ echo $count 7 220 $ @ result = ( $count < 5 ) 221 $ echo $result 0 222 $ @ count += 5 223 $ echo $count 12 224 $ @ count++ 225 $ echo $count 13 Event 216 declares the variable count and assigns it a value of 0. Event 218 shows the result of an arithmetic operation being assigned to a variable. Event 220 uses @ to assign the result of a logical operation involving a constant and a variable to result. The value of the operation is false (= 0) because the variable count is not less than 5. Event 222 is a compressed form of the following assignment statement: tcsh $ @ count = $count + 5 Event 224 uses a postfix operator to increment count by 1. Postincrement and postdecrement operators You can use the postincrement (++) and postdecrement () operators only in expressions containing a single variable name, as shown in the following example: tcsh $ @ count = 0 tcsh $ @ count++ tcsh $ echo $count 1 tcsh $ @ next = $count++ @: Badly formed number. Unlike in the C programming language and bash, expressions in tcsh cannot use preincrement and predecrement operators. Arrays of Numeric VariablesYou must use the set builtin to declare an array of numeric variables before you can use @ to assign values to the elements of that array. The set builtin can assign any values to the elements of a numeric array, including zeros, other numbers, and null strings. Assigning a value to an element of a numeric array is similar to assigning a value to a simple numeric variable. The only difference is that you must specify the element, or index, of the array. The syntax is @ variable-name[index] operator expression The index specifies the element of the array that is being addressed. The first element has an index of 1. The index cannot be an expression but must be either a numeric constant or a variable. In the preceding syntax the brackets around index are part of the syntax and do not indicate that index is optional. If you specify an index that is too large for the array you declared with set, tcsh displays @: Subscript out of range. 226 $ set ages = (0 0 0 0 0) 227 $ @ ages[2] = 15 228 $ @ ages[3] = ($ages[2] + 4) 229 $ echo $ages[3] 19 230 $ echo $ages 0 15 19 0 0 231 $ set index = 3 232 $ echo $ages[$index] 19 233 $ echo $ages[6] ages: Subscript out of range. Elements of a numeric array behave as though they were simple numeric variables. Event 226 declares an array with five elements, each having a value of 0. Events 227 and 228 assign values to elements of the array, and event 229 displays the value of one of the elements. Event 230 displays all the elements of the array, 232 specifies an element by using a variable, and 233 demonstrates the out-of-range error message. BracesLike with bash, tcsh allows you to use braces to distinguish a variable from surrounding text without the use of a separator: $ set bb=abc $ echo $bbdef bbdef: Undefined variable. $ echo ${bb}def abcdef Special Variable FormsThe special variable with the following syntax has the value of the number of elements in the variable-name array: $#variable-name You can determine whether variable-name has been set by looking at the value of the variable with the following syntax: $?variable-name This variable has a value of 1 if variable-name is set and 0 otherwise: tcsh $ set days = (mon tues wed thurs fri) tcsh $ echo $#days 5 tcsh $ echo $?days 1 tcsh $ unset days tcsh $ echo $?days 0 Reading User InputWithin a tcsh shell script, you can use the set builtin to read a line from the terminal and assign it to a variable. The following portion of a shell script prompts the user and reads a line of input into the variable input_line: echo -n "Enter input: " set input_line = "$<" The value of the shell variable $< is a line from standard input. The quotation marks around $< keep the shell from assigning only the first word of the line of input to the variable input_line. Shell VariablesTC Shell variables may be set by the shell, inherited by the shell from the environment, or set by the user and used by the shell. Some variables take on significant values (for example, the PID number of a background process). Other variables act as switches: on if they are declared and off if they are not. Many of the shell variables are often set from one of tcsh's two startup files: ~/.login and ~/.tcshrc (page 340). Shell Variables That Take on Valuesargv Contains the command line arguments (positional parameters) from the command line that invoked the shell. Like all tcsh arrays, this array uses one-based indexing; argv[1] contains the first command line argument. You can abbreviate references to $argv[n] as $n. The token argv[*] references all the arguments together; you can abbreviate it as $*. Use $0 to reference the name of the calling program. Refer to "Positional Parameters" on page 564. The Bourne Again Shell does not use the argv form, only the abbreviated form. $#argv or $# Holds the number of elements in the argv array. Refer to "Special Variable Forms" on page 357. autolist Controls command and variable completion (page 349). autologout Enables tcsh's automatic logout facility, which logs you out if you leave the shell idle for too long. The value of the variable is the number of minutes of inactivity that tcsh waits before logging you out. The default is 60 minutes if you are Superuser. This variable is initially unset for other users. cdpath Affects the operation of cd in the same way as the CDPATH variable does in bash (page 290). The cdpath variable is assigned an array of absolute pathnames (see path, later in this section) and is usually set in the ~/.login file with a command line such as the following: tcsh $ set cdpath = (/Users/sam /Users/sam/letters) When you call cd with a simple filename, it searches the working directory for a subdirectory with that name. If one is not found, cd searches the directories listed in cdpath for the subdirectory. correct Set to cmd for automatic spelling correction of command names, to all to correct the entire command line, and to complete for automatic completion of command names. This variable works on corrections that are made after you press RETURN. Refer to "After You Press RETURN" on page 351. cwd The shell sets this variable to the name of the working directory. When you access a directory through a symbolic link (page 105), tcsh sets cwd to the name of the symbolic link. dirstack The shell keeps the stack of directories used with the pushd, popd, and dirs builtins in this variable. For more information refer to "Manipulating the Directory Stack" on page 275. fignore Holds an array of suffixes that tcsh ignores during filename completion.] gid The shell sets this variable to your group ID. histfile Holds the full pathname of the file that saves the history list between login sessions (page 343). The defaults is ~/.history. history Specifies the size of your history list. Refer to "History" on page 342. home or HOME Holds the pathname of the user's home directory. The cd builtin refers to this variable, as does the filename substitution of ~ (page 324). Specifies files and directories to check for mail. The TC Shell checks for new mail every 10 minutes unless the first word of mail is a number, in which case that number specifies how often the shell should check in seconds. owd The shell keeps the name of your previous (old) working directory in this variable, which is equivalent to ~ in bash. path or PATH Holds a list of directories that tcsh searches for executable commands (page 285). If this array is empty or unset, you can execute commands only by giving their full pathnames. You can set path with a command such as the following: tcsh $ set path = ( /usr/bin /bin /usr/local/bin /usr/bin/X11 ~/bin . ) prompt Holds the primary prompt, similar to the bash PS1 variable (page 286). If it is not set, the prompt is >, or # for root (Superuser). The shell expands an exclamation point in the prompt string to the current event number. The following is a typical line from a .tcshrc file that sets the value of prompt: set prompt = '! $ ' Table 9-4 lists a number of special formatting sequences you can use in prompt to achieve special effects.
prompt2 Holds the prompt used in foreach and while control structures (pages 369 and 371). The default value is '%R?', where R is replaced by the word while if you are inside a while structure and foreach if you are inside a foreach structure. prompt3 Holds the prompt used during automatic spelling correction. The default value is 'CORRECT>%R (y|n|e|a)?', where R is replaced by the corrected string. savehist Specifies the number of commands saved from the history list when you log out. These events are saved in a file named ~/.history. The shell uses these events as the initial history list when you log in again, causing your history list to continue across login sessions (page 343). shell Holds the pathname of the shell you are using. shlvl Is incremented each time you start a subshell and decremented each time you exit a subshell. The value is set to 1 for login a shell. status Contains the exit status returned by the last command. Similar to $? in bash (page 564). tcsh Holds the version number of tcsh that you are running. time Provides two functions: automatic timing of commands using the time builtin and the format used by time. You can set this variable to either a single numeric value or an array holding a numeric value and a string. The numeric value is used to control automatic timing; any command that takes more than that number of CPU seconds to run has time display the command statistics when it finishes execution. A value of 0 results in statistics being displayed after every command. The string controls the formatting of the statistics using special formatting sequences, including those listed in Table 9-5.
By default the time builtin uses the string "%Uu %Ss %E %P% %X+%Dk %I+%Oio %Fpf+%Ww" which generates output in the following format: tcsh $ time 0.200u 0.340s 17:32:33.27 0.0% 0+0k 0+0io 1165pf+0w You can time commands when you are concerned about system performance. If your commands consistently show many page faults and swaps, your system is probably memory starved and you should consider adding more memory to the system. You can use the information that time reports to compare the performance of various system configurations and program algorithms. tperiod Controls how often, in minutes, the shell executes the special periodic alias (page 345). user The shell sets this variable to your username. version The shell sets this variable to contain detailed information about the version of tcsh you are using. watch Set to an array of user and terminal pairs to watch for logins and logouts. The word any means any user or any terminal, so (any any) monitors all logins and logouts on all terminals, and (sam ttyp1 any console $user any) watches for sam on ttyp1, any user who accesses the system console, and any logins and logouts that use your account (presumably to catch intruders). By default logins and logouts are checked once every 10 minutes, but you can change this value by beginning the array with a numeric value giving the number of minutes between checks. If you set watch to (1 any console), logins and logouts by any user on the console will be checked once a minute. Reports are displayed just before a new shell prompt is issued. Also, the log builtin forces an immediate check whenever it is executed. See who for information about how you can control the format of the watch messages. who Controls the format of the information displayed in watch messages (Table 9-6).
The default string used for watch messages when who is unset is "%n has %a %l from %m", which generates the following line: jenny has logged on ttyp2 from localhost $ As in bash, this variable contains the PID number of the current shell; use it as $$. Shell Variables That Act as SwitchesThe following shell variables act as switches; their values are not significant. If the variable has been declared, the shell takes the specified action. If not, the action is not taken or is negated. You can set these variables in your ~/.tcshrc startup file, in a shell script, or from the command line. autocorrect Causes the shell to attempt spelling correction automatically, just before each attempt at completion. dunique Normally pushd blindly pushes the new working directory onto the directory stack, meaning that you can end up with many duplicate entries on this stack. Set dunique to cause the shell to look for and delete any entries that duplicate the one it is about to push. echo Causes the shell to display each command before it executes that command. Set echo by calling tcsh with the x option or by using set. filec Enables filename completion (page 348) when running tcsh as csh (and csh is linked to tcsh). histlit Displays the commands in the history list exactly as entered, without interpretation by the shell (page 344). ignoreeof Prevents you from using CONTROL-D to exit from a shell so you cannot accidentally log out. When this variable is declared, you must use exit or logout to leave a shell. listjobs Causes the shell to list all jobs whenever a job is suspended. listlinks Causes the IsF builtin to show the type of file each symbolic link points to instead of marking the symbolic link with an @ symbol. loginsh Set by the shell if the current shell is running as a login shell. nobeep Disables all beeping by the shell. noclobber Prevents you from accidentally overwriting a file when you redirect output and prevents you from creating a file when you attempt to append output to a nonexistent file (Table 9-7). To override noclobber, add an exclamation point to the symbol you use for redirecting or appending output (for example, >! and >>!). For more information see page 125.
noglob Prevents the shell from expanding ambiguous filenames. Allows you to use *, ?, ~, and [] on the command line or in a shell script without quoting them. nonomatch Causes the shell to pass an ambiguous file reference that does not match a filename to the command that is being called. The shell does not expand the file reference. When you do not set nonomatch, tcsh generates a No match error message and does not execute the command. tcsh $ cat questions? cat: No match tcsh $ set nonomatch tcsh $ cat questions? cat: questions?: No such file or directory notify When set, tcsh sends a message to the screen immediately whenever a background job completes. Ordinarily tcsh notifies you about job completion just before displaying the next prompt. Refer to "Job Control" on page 272. pushdtohome Causes a call to pushd without any arguments to change directories to your home directory (equivalent to pushd ). pushdsilent Causes pushd and popd not to display the directory stack. rmstar Causes the shell to request confirmation when you give an rm * command. verbose Causes the shell to display each command after a history expansion (page 342). Set verbose by calling tcsh with the v option or by using set. visiblebell Causes audible beeps to be replaced by flashing the screen. |