简体   繁体   中英

Shell script variable value

I have value 0.000000 written in a file. I open the file and assign it to a variable. But when i compare it's value like if [ "$var" -eq "0.000000" ] it doesn't evaluate to true. What could be the reason?

Moreover, if the file has just 0, and if i compare it's value [ "$var" -eq "0" ] it evaluates as expected to true.

As Fredrik (+1 for him) said, bash does not support floating point. If you must, use string comparison:

if [ "$var" = "0.000000" ]

You might switch to ksh which supports floating point arithmetic:

$ bash
a=0.00000
[ $a -eq 0 ] && echo ok || echo ko
bash: [: 0.00000: integer expression expected
ko
$ ksh
$ a=0.00000
$ [ $a -eq 0 ] && echo ok || echo ko
ok
$ a=0.00001
$ [ $a -eq 0 ] && echo ok || echo ko
ko

bash can't understand floats. Try using bc , which will return 1 if the equality is true, 0 otherwise.

if [ $(bc <<< $var==0.000000) -eq 1 ]
then

fi

or expr :

if [ $(expr $var == 0.000000) -eq 1 ]
then

fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM