Operating System - HP-UX
1824123 Members
4114 Online
109668 Solutions
New Discussion юеВ

Performing simple math calculations in 'sh"

 
SOLVED
Go to solution
john guardian
Super Advisor

Performing simple math calculations in 'sh"

Hi. I usually use ksh, but need to run "sh" instead. As an example, I've used

typeset -i
typeset -i
=-
echo $

but that doesn't seem to be supported for sh.

Can anyone suggest an alternate method for performing this type of operation?

Would some form of "eval" work?

Thanks.
7 REPLIES 7
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Performing simple math calculations in 'sh"

Note the "sh" in HP-UX does not mean the Bourne shell but rather the POSIX shell (which is all but identical to the Korn shell). Your syntax wouldn't work in ksh either.

typeset -i A=100
typeset -i B=50
typeset -i C=0

C=$((${A} - ${B}))
echo "Result = ${C}"

This syntax also works in ksh.
If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: Performing simple math calculations in 'sh"

Hi Joe:

One way:

# typeset -i var1=1
# typeset -i var2=3
# let var3=var1+var2
# echo ${var3}

Another way, in lieu of using 'let' is:

# var3=$(( $var1 + $var2 ))

Regards!

...JRF...
Jonathan Fife
Honored Contributor

Re: Performing simple math calculations in 'sh"

I like:

$ echo $SHELL
/sbin/sh
$ var2=30
$ var3=15
$ (( var1 = var2 - var3 ))
$ echo $var1
15
Decay is inherent in all compounded things. Strive on with diligence
Carsten Krege
Honored Contributor

Re: Performing simple math calculations in 'sh"

You can use the following. Also see sh-posix manual page and seach for "Arithmetic Evaluation".

# i=$(( 5 + 6 ))
# echo $i
11
# i=$(( 5 - 6 ))
# echo $i
-1

# typeset -i a
# typeset -i b
# a=10
# b=12
# i=$(( $a - $b ))
# echo $i
-2

Carsten
-------------------------------------------------------------------------------------------------
In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move. -- HhGttG
Bill Hassell
Honored Contributor

Re: Performing simple math calculations in 'sh"

There are 3 ways for shell arithmetic (which by the way is only integer, no fractions):

1. let A=$B+$C
2. A=$(($A+$B))
3. A=$(expr $B + $C)


Bill Hassell, sysadmin
john guardian
Super Advisor

Re: Performing simple math calculations in 'sh"

Hi. Thanks to all for input. Sorry about the points delay. The input for this has been running flawlessly. Regards.
john guardian
Super Advisor

Re: Performing simple math calculations in 'sh"

Thanks to all.