Monday, December 31, 2012

Arithmatic Expression in shell script

The below code snippet shows how do the arithmatic expression in shell script.

-bash-3.2$ cat arithmatic_sh

#!/bin/bash
let "z=5**3"    # 5 * 5 * 5
echo "z = $z"   # z = 125
expr 5 % 3      #2


n=1; echo -n "$n "
let "n = $n + 1"   # let "n = n + 1"  also works.
echo -n "$n "

(( n = n + 1 ))
#  A simpler alternative to the method above.
echo -n "$n "

n=$(($n + 1))
echo -n "$n "

(( n++ ))          # (( ++n ))  also works.
echo -n "$n "
echo

exit 0

Output :

-bash-3.2$ sh arithmatic_sh
z = 125
2
1 2 3 4 5
-bash-3.2$

let "z=5**3"        -->  5*5*5 assigned into variable z (5 will be multiply by 3 times)



some thing special in mulitplication

-bash-3.2$ cat simple_multiplication
echo Enter the multiplication number required:
read number
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "$number * $i =`expr $number \* $i`" # slash star is important bz it differenciate from regular exp
done


OUTPUT :

-bash-3.2$ sh simple_multiplication
Enter the multiplication number required:
2
2 * 1 =2
2 * 2 =4
2 * 3 =6
2 * 4 =8
2 * 5 =10
2 * 6 =12
2 * 7 =14
2 * 8 =16
2 * 9 =18
2 * 10 =20
-bash-3.2$

No comments:

Post a Comment

Price List Query for Item

 SELECT qph.list_header_id,        qph.name,        qph.description,        qphh.start_date_active,        qphh.currency_code,        q...