PDA

View Full Version : How to use decimals in while loop in shell script


alice06
Feb16-11, 02:01 PM
Hi all

I hav written a very small shell script in bin bash & its not working. The script is ::

#!/bin/bash
i=1.0
while [ $i -le 3.0 ]
do
i=`expr "$i + 0.5" | bc`;
echo "i=$i"
done

The error is : line 6: [: 1.0: integer expression expected

I think the use of decimals in the while loop is creating problems.

Please help, in urgent need.

Regards
Alice

Grep
Feb16-11, 02:46 PM
I don't write many shells scripts these days, but you're probably right about the decimals in the while loop causing problems. So I just did this:

#!/bin/bash
i="1"
while [ $i -le 6 ]
do
i=$[$i+1]
j=`expr "scale=1;$i.0/2.0" | bc`;
echo "i=$j"
done

A quickie job, but it seems to work. Had to set the scale in bc to 1 or it truncates the decimals.

alice06
Feb17-11, 01:14 AM
Hey Grep, Thanx a ton for replying.

Grep, although ur script doesnt give all the numbers -le 6 (or the nuber we specify), but wid a minor modification in ur script, I was able to get my job done perfectly.

Thanx for helping me out, thank u very much.

Regards
Alice

TylerH
Feb17-11, 02:18 AM
You should try perl. It's good for this type of stuff.

Grep
Feb17-11, 02:41 AM
Grep, although ur script doesnt give all the numbers -le 6 (or the nuber we specify), but wid a minor modification in ur script, I was able to get my job done perfectly.

No problem at all, alice. Glad to help. Figured it might not be outputting exactly the right numbers, but the basic problem was solved, at least (as I said, quickie job). Glad you got it doing what you wanted.
You should try python. It's good for this type of stuff.
Fixed that for ya. :wink: o:)

alice06
Feb17-11, 07:42 AM
Yes, hav to learn Pearl/Python or something soon.
Thank u all for helping me out.

Big Thanx

Regards
Alice