Simple math in shell script

Feb 11, 2006 4 Replies

I really don't know how bc/dc work. I need to do some really simple math in a Bourne script. But there are decimal places, so I can't use



$(( expression ))



(which otherwise would work as a shell built-in).



E.g., what's the syntax for finding



$X / 100 + 1



?

I wish the man pages had damn example sections!



Thanks.



Dallman


I haven't used the Bourne shell for a long time and don't even have a system up at the moment which has it but I do recall that bc is the way to do floating point math within it. As for man pages not having examples, I guess it depends on who's man pages you are looking at. My old AT&T SVR4 man pages sure had examples. You might look at

formatting link
which has some examples given.

BTW: this seems a _really_ silly group for this posting.

Using bash....

x=`expr $x / 100 + 1` for x=200 will return a value of 3 since 200/100=2 and then add 1.

But if you were to: x=20000000;y=`expr 100 + 1`;x=`expr $x / $y` You get: 198019

Yeah...there's probably an easier way to do it.

Should have thought of this before: If $X is amenable, you can probably just perform the math as fixed-point by removing the decimal, calculating, and then re-insert the decimal in the proper location afterwards.

In , John McGaw spake thusly:

Ah. That's much better than the man page I have. Thanks!

You're right, and I apologize. I'm red-faced, but I thought I was in another group when I made that post. I'm surprised you guys didn't flame the hell out of me! Thanks. Your and Steve's answers were useful.

Regards, Dallman

Join the Discussion

Have something to add? Share your thoughts — no account required.

Didn't find your answer?

Ask the community — no account required