Prev | Current Page 359 | Next

Michael McCallister

"openSUSE Linux Unleashed"

This was
extremely clunky:
rich@testing:~> expr 1 + 5
6
rich@testing:~> expr 5 \* 2
10
Note that the multiplication symbol (*) must be preceded by a backslash to prevent the
shell from recognizing it as a wildcard character.
Using the expr command in a shell script was equally cumbersome:
#!/bin/bash
# An example of using the expr command
var1=10
var2=20
var3=`expr $var2 / $var1`
echo The result is $var3
To assign the result of a mathematical equation to a variable, you had to use the back
quote to extract the output from the expr command.
While the bash shell fully supports the expr command, it also includes a much easier way
of performing mathematical equations. In bash, when assigning a value to a variable, you
can enclose a mathematical equation using square brackets ([]). The shell interprets
anything within the square brackets as a mathematical equation to evaluate:
rich@testing:~> var1=$[1 + 5]
rich@testing:~> echo $var1
6
rich@testing:~> var2 = $[$var1 * 2]
CHAPTER 8 Shaking Hands with Your Shell 154
rich@testing:~> echo $var2
12
rich@testing:~>
Using square brackets makes shell math much easier.


Pages:
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
news przasnysz ogłoszenia news news news