Jump to content

How to use decimals in while loop in a shell script

- - - - -

  • Please log in to reply
5 replies to this topic

#1
alice06

alice06

    Newbie

  • Members
  • PipPip
  • 14 posts
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

#2
DarkLordofthePenguins

DarkLordofthePenguins

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 409 posts
The bash shell doesn't have decimal or floating point types, only strings, integers, and arrays. If you want to use a decimal, either use ksh or emulate floating point arithmetic by using larger numbers and then inserting the decimal point in the output with sed or something. For instance:


#!/bin/bash

declare -i i=10

# use the number multiplied by 10

while [ $i -le 30 ]

do

	i=`expr "$i + 5" | bc`;

	 echo "i=$i" | sed "s/[0-9]$/\.&/" # sed inserts a decimal point before the last digit

done


I used "declare -i" here because otherwise, i is interpreted as a string, not an integer.
Programming is a journey, not a destination.

#3
alice06

alice06

    Newbie

  • Members
  • PipPip
  • 14 posts
Hey DarkLordofthePenguins, Thanx a ton for replying.

Wid ur script, I was able to get my job done perfectly.

Thanx for helping me out, thank u very much.

Regards
Alice

#4
Smilex

Smilex

    Learning Programmer

  • Members
  • PipPipPip
  • 84 posts
I read once that you should never use decimals for conditions and loops, I'm not so sure about this, so if there's anyone who knows better who could clarify that? :P
P.S: I didn't want to make a new thread just for that, since it's kind of on-topic here. I hope that's no problem? :P

#5
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200

Smilex said:

I read once that you should never use decimals for conditions and loops

Fixed precision decimal numbers are likely to be incorrectly represented, 0.7 + 0.7 can often lead to 1.5 and other havok depending on the system and how the program uses them.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#6
Smilex

Smilex

    Learning Programmer

  • Members
  • PipPipPip
  • 84 posts
thanks for the clarification




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users