z/OS UNIX System Services User's Guide
Previous topic | Next topic | Contents | Contact z/OS | Library | PDF


Calculating with variables

z/OS UNIX System Services User's Guide
SA23-2279-00

Suppose you run the following commands either in a shell script or by typing in one command after another:
set i=1
set j=$i+1
echo $j
The output of echo is 1+1, because a normal variable assignment assigns a string to a variable. Thus j gets the string 1+1.
To evaluate an arithmetic expression, you can enter:
@ variable=expression
This command line assigns the value of an expression to the given variable. For example:
i=1
@ j=$i + 1
echo $j
Here j is assigned the value of the expression and the echo command displays the value 2.
You can also use @ to change the value of a variable. If you enter:
i=1
@ i=$i + 1
echo $i
the @ command changes the value of i. The new value of i is the old value plus 1.
An @ command can have any of the standard arithmetic expressions:
-A
Negative A
A * B
A times B
A / B
A divided by B
A % B
Remainder of A divided by B
A + B
A plus B
A - B
A minus B
The standard mathematical order of operations is used, as shown in the way that operations are grouped:
  • All unary minus operations are carried out;
  • Then any *, /, or % operations (from left to right in the order they appear);
  • Then any additions or subtractions (from left to right in the order they appear).
Many operators use special shell characters, so you usually need to put double quotation marks around the expression. Thus:
@ i =  5 + 2 * 3
assigns 11 to i, because the multiplication is done first. You can use parentheses in the usual way to change the order of operations. For example:
@ i = ((5 + 2) * 3 )
assigns 21 to i.
Note: @ does not work with numbers that have fractional parts. It works only with integers.

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014