Sunday, March 2, 2014

Unix Shell Scripting–Expr

- The Bourne shell has no notion of a number (only strings), and as such incapable of doing numerical calculations

- However, there is a UNIX program called “expr” which was designed specifically for this purpose.

- It works like this:

[oracle@rac1 ~]$ expr 3 + 5
8
Note: There should be space before and after numerical operator (+, –, *, / etc)

Multiplication can be done using *, but * is also used for wildcard by Unix, so multiplications one should escape using backslash like below

[oracle@rac1 ~]$ expr 3 * 4
expr: syntax error
[oracle@rac1 ~]$ expr 3 \* 4
12

- To assign the output of an expr to a other variable, the expression need to placed in the backquotes (as expr is a Unix command and we are working with $ and variables)

oracle@rac1 ~]$ a=15
[oracle@rac1 ~]$ b=3
[oracle@rac1 ~]$ c=expr $a / $b
bash: 15: command not found  <===  without back quotes Unix considers the literal value of $a (which is 15) and throws the error saying 15 is not a command in bash.
[oracle@rac1 ~]$ c=`expr $a / $b`
[oracle@rac1 ~]$ echo $c
5

- Example of using expr in loops:

echo -n "Enter the counter to loop: "
read count

i=1

while [ $i -le $count ]
do
echo "This is loop number $i"
i=`expr $i + 1`
done

Enter the counter to loop: 5
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4
This is loop number 5

No comments:

Post a Comment