How to use decimals in while loop in shell script

  • Thread starter Thread starter alice06
  • Start date Start date
  • Tags Tags
    Loop Shell
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 5K views
alice06
Messages
6
Reaction score
0
Hi all

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

Code:
#!/bin/bash
i=1.0
while [ $i -le 3.0 ]
do
	i=`expr "$i + 0.5" | bc`;
	 echo "i=$i"
done
The error is :
Code:
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
 
Physics news on Phys.org
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:
Code:
#!/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.
 
Hey Grep, Thanx a ton for replying.

Grep, although ur script doesn't 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
 
You should try perl. It's good for this type of stuff.
 
alice06 said:
Grep, although ur script doesn't 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.
TylerH said:
You should try python. It's good for this type of stuff.
Fixed that for ya. :wink: o:)
 
Yes, have to learn Pearl/Python or something soon.
Thank u all for helping me out.

Big Thanx

Regards
Alice