Expressions are used in @ (the C shell math operator), if, and while statements to perform arithmetic, string comparisons, file testing, etc. exit and set can also specify expressions. Expressions are formed by combining variables and constants with operators that resemble those in the C programming language. Operator precedence is the same as in C. It is easiest to just remember the following precedence rules:
* / %
+ -
Group all other expressions inside ()
s; parentheses are required if the expression contains <
, <
, &
, or |
Operators can be one of the following types.
Operator | Description |
---|---|
= | Assign value. |
+= -= | Reassign after addition/subtraction. |
*= /= %= | Reassign after multiplication/division/remainder. |
&= ^= |= | Reassign after bitwise AND/XOR/OR. |
++ | Increment. |
-- | Decrement. |
Operator | Description |
---|---|
* / % | Multiplication; integer division; modulus (remainder). |
+ - | Addition; subtraction. |
Command substitution and filename expansion are performed on file before the test is performed.
Operator | Description |
---|---|
-d file | The file is a directory. |
-e file | The file exists. |
-f file | The file is a plain file. |
-o file | The user owns the file. |
-r file | The user has read permission. |
-w file | The user has write permission. |
-x file | The user has execute permission. |
-z file | The file has zero size. |
! | Reverse the sense of any inquiry above. |
The following examples show @ commands and assume n
= 4.
Expression | Value of $x |
---|---|
@ x = ($n > 10 || $n < 5) | 1 |
@ x = ($n >= 0 && $n < 3) | 0 |
@ x = ($n << 2) | 16 |
@ x = ($n >> 2) | 1 |
@ x = $n % 2 | 0 |
@ x = $n % 3 | 1 |
The following examples show the first line of if or while statements.
Expression | Meaning |
---|---|
while ($#argv != 0) | While there are arguments ... |
if ($today[1] == "Fri") | If the first word is "Fri"... |
if ($file !~ *.[zZ]) | If the file doesn't end with |
if ($argv[1] =~ chap?) | If the first argument is |
if (-f $argv[1]) | If the first argument is a plain file ... |
if (! -d $tmpdir) | If $tmpdir is not a directory ... |