8.4. ExpressionsThe C shell supports string, arithmetic, and file-oriented expressions. Let's take a look at each kind of expression. 8.4.1. String ExpressionsThe C shell supports the string operators listed in Figure 8-9.
If either operand is a list, then the first element of the list is used for the comparison. The script in the following example used the string-matching technique to infer a user's response: % cat expr1.csh ...list the script. # echo -n "do you like the C shell? " #prompt. set reply = $< # get a line of input. if ($reply == "yes") then #check for exact match. echo you entered yes else if ($reply =~ y*) then #check for inexact match. 8.4.2. Arithmetic ExpressionsThe C shell supports the arithmetic operators listed in Figure 8-10, in descending order of precedence.
These operators work just like their standard C counterparts, except that they can only operate on integers. Expressions may be surrounded by parentheses to control the order of evaluation. When an arithmetic expression is evaluated, a null string is equivalent to zero. Any expression that uses the &, &&, ||, |, <, >, <<, or >> operators must be surrounded by parentheses to prevent the shell from interpreting these characters specially. Here's a sample script that uses a couple of operators: % cat expr3.csh ...list the script. # set a = 3 set b = 5 if ($a > 2 && $b > 4) then echo expression evaluation seems to work endif % tcsh expr3.csh ...execute the script. expression evaluation seems to work % _ To assign the result of an expression to a variable, you may not use the set command. Instead, use the built-in @ command, which has the forms shown in Figure 8-11.
Here are some examples: % set a = 2 * 2 ...you can't use set for assignment set: Syntax error. % @ a = 2 * 2 ...use @ instead. % echo $a 4 % @ a = $a + $a ...add two variables. % echo $a 8 % set flag = 1 % @ b = ($a && $flag) ...need ()s because of &&. % echo $b 1 % @ b = ($a ^ $flag) % echo $b 0 % _ You may also increment or decrement a variable by using ++ or --. For example: % set value = 1 % @ value ++ % echo $value 2 % _ 8.4.3. File-Oriented ExpressionsTo make file-oriented decisions a little easier to program, the C shell supports several file-specific expressions. Each expression is of the form given in Figure 8-12.
Figure 8-13 describes each option.
Here's an example script that uses the -w option to determine whether a file is writable or not: % cat expr4.csh ...list the script. # echo -n "enter the name of the file you wish to erase: " set filename = $< # get a line of input. if (! (-w "$filename")) then # check I have access. echo you do not have permission to erase that file. else rm $filename echo file erased endif % tcsh expr4.csh ...execute the script. |