Operating System - HP-UX
1847240 Members
2937 Online
110263 Solutions
New Discussion

shell arithmetic operations

 
SOLVED
Go to solution
andi_1
Frequent Advisor

shell arithmetic operations

Hi guys,

tmp=$extra/100
echo "tmp is $tmp" // displayes 10/100

I also tried the following:
tmp=`expr $extra / 100` // same thing

Does anyone know the best way to perform arithmetic operations in shell?

Thank you.
9 REPLIES 9
Frederic Sevestre
Honored Contributor
Solution

Re: shell arithmetic operations

hi,

try
let tmp=extra/100

It should work,
Fr??d??ric
Crime doesn't pay...does that mean that my job is a crime ?
Francois Bariselle_3
Regular Advisor

Re: shell arithmetic operations

In C-shell:

set num1 = 8
set num2 = 2

@ num = ( ${num1} / ${num2} )
echo ${num}

result :

4

See :

man csh

Frank
Fais la ...
A. Clay Stephenson
Acclaimed Contributor

Re: shell arithmetic operations

Try this:

A=300
B=10
C=$(( ${A} / ${B} ))
echo "C = ${C}"

Note: The shell does integer arithmetic.
If it ain't broke, I can fix that.
Deshpande Prashant
Honored Contributor

Re: shell arithmetic operations

Hi
Try this
TMP=100
TMP1=10

let TMP2=${TMP}/${TMP1}
echo $TMP2 will display 10

Thanks.
Prashant Deshpande.

Take it as it comes.
Kong Kian Chay
Regular Advisor

Re: shell arithmetic operations

Leon

* You should have a space before & after the arithmetic sign. Examples :

expr 4 + 3 (gives 7)
expr 4 / 2 (gives 2)
expr 4 \* 3 (gives 12)

Deshpande Prashant
Honored Contributor

Re: shell arithmetic operations

Also Try

TMP=100
TMP1=10
((TMP2=TMP/TMP1))
echo $TMP2 will display 10

Thanks.
Prashant Deshpande.
Take it as it comes.
Roger Baptiste
Honored Contributor

Re: shell arithmetic operations

tmp=`echo $extra/100 | bc`
echo "tmp is $tmp"


-raj
Take it easy.
James R. Ferguson
Acclaimed Contributor

Re: shell arithmetic operations

Hi Leon:

As already noted, the shell provides integer arithmetic. If you want to incorporate real numbers, 'bc' provides a convenient vehicle. Choose the 'scale' to set the precision you want:

# X=1;Y=8;echo "scale=3\n $X/$Y"|bc

You can also leverage 'awk' and couple it with 'printf' to format output in different number bases:

# X=1;Y=8;echo "$X $Y"|awk '{printf "%.4f\n",$1/$2}'

# X=7;Y=8;echo "$X $Y"|awk '{printf "%4x\n",$1+$2}'

Regards!

...JRF...
Magdi KAMAL
Respected Contributor

Re: shell arithmetic operations

Hi Leon,

Here are the basic arithmetic operations :

1. Addition :
# expr 8 + 2
10

2. substraction :
# expr 8 - 2
6

3. Division :
# expr 8 / 2
4

4. Multiplication :
# expr 8 \* 2
16

Magdi