
How do I compare float / real numbers in a shell script?Hi i am trying to comapre numbers for the biggest among double type of numbers. For example: 0.254, 0.255, 0.564, 0.984, 0.556, 0.6566, and 0.5666. I'm using the following script code: if [ $max -lt $i ] But they all give the error message "integer expression expected". Help! The shell is doing exactly what it should be doing, believe it or not. Shell scripts can't really do proper mathematics, just piddly little simple integer math. So when you give it a number like 0.245 it sees "0" and some gobbledygook that it can't figure out, hence the error message. There are two ways you can solve this. The first is to actually use some sort of more sophisticated mathematical tool like bc to push out the conditional expression, then test its return value to see if your condition was met or not. That's a bit tricky, particularly since bc can be difficult to use. Instead, if indeed your input is always 0.something then I suggest that you can exploit that and simply strip off the "0." prefix, then compare them as integers and get exactly the result you seek. Here's how I'd solve that: #!/bin/sh
max=0 while read value do val="$(echo $value | sed 's/0.//')" if [ $val -gt $max ] then max=$val fi done echo "max value is 0.$max" exit 0 That should do what you seek as long as your input is always well-formed. Really, if this is going to be something that gets a lot of use, I'd probably also add some code that checks to ensure that the inputs all start with "0." to be sure it never breaks too.
Help others find this article at Del.icio.us, Digg, Netscape, Reddit, and Simpy.
Categorized:
Shell Script Programming
(Article 7141)
Tagged: scripting, shell scripts Previous: Can I get into trouble for downloading illegal files? Next: How do I delete Mac Dashboard widgets? Subscribe!
Never miss another useful Q&A article again! Subscribe to AskDaveTaylor with Google Reader. If you simply strip off the "0.", then "0.984" will appear to be a smaller integer than "0.6566", but if you compare the originals as strings (dictionary order), then the result would be correct. Unfortunately, neither of these approaches works when you have different numbers of digits before and after the decimal point. Then you'd have to "normalize" by adding leading or trailing zeroes depending on whether you want to use string comparison or integer comparison. Posted by: Paul Kosinski at January 21, 2007 9:23 PM(sound of me slapping my head) Doh! You're absolutely right, Paul. I'll dig into this and come up with a different solution, just for completion. :-) Posted by: Dave Taylor at January 21, 2007 10:23 PMThis question touches on a limitation of the Bash shell--namely, that it does not understand floating point arithmetic and treats such numbers as strings. Bash documentation even goes on to say this: "When not to use shell scripts So the work-arounds are indirect and perhaps (for some) counter-intuitive. One simple way to fix your code in place is to pipe your input (presumably shell variables) to bc(1), an arbitrary precision calculator language. An example follows below: if [ $max -lt $i ] becomes: if [ $(echo "$max < $i"|bc) -eq 1 ] Where you're using a temporary subshell invocation to calculate and return a value for the test brackets. The comparison against 1 ("-eq 1") is necessary. This is the 'quickest' and smallest solution I can see to your problem, but I'm sure there are (better?) alternative methods. Hope that helps. Posted by: Justin K. at February 5, 2007 11:43 AMHello. This might make a good interview question for a toolsmith SysAdmin. Here's a script I wrote in answer. It includes flt and fgt functions, that use sort -n, as well as a test harness. Seems to work okay on this LINUX box: #!/bin/sh function fgt () { min=`(echo $LHS ; echo $RHS) | sort -n | head -1` function flt () { min=`(echo $LHS ; echo $RHS) | sort -n | head -1` echo -n "$FUNC $ARG1 $ARG2 ... " if [ $? -eq 0 ]; then true_or_false fgt 1.2 3.4
> ./fgt.sh Dave perhaps you can re-insert the PRE tags. ;) Cheers, The one posted by Justin K is really a quick way of doing that, it helped me. Thanks Justin. use simply awk,like: a=1.2 The korn shell ( open source from at&t research ) has had if (( max < i )); then ... ; fi On the other hand, I would not use 'i' for a floating point Plug: ksh93 gets shipped with some versions of unix and linux. Source and binaries can be found at at&t via kornshell.com. Henk Posted by: Henk Langeveld at March 18, 2007 12:26 PMsir, and how to find the maximum values among the no.s???? please give the answer with one or two examples. We can use tr+sort+head or tail to get high and low values #To get Highest value #To get Lowest value #To see for yourself sorry for the above typo: please use this for Lowest value: #To get Lowest value How do I make complex floating operation in a linux script. If I try "100 / 500 | bc" it returns 0, instead of 0.20. Posted by: Shashank at July 24, 2007 12:27 AMRight, Shashank. You need to be a bit more tricky because the default setting for "bc" is to have zero digits after the decimal point. What you need to do is feed the statement "scale=2" or similar to get any precision at all. I explain it -- with lots of examples -- in my book Wicked Cool Shell Scripts, which you can learn about at http://www.intuitive.com/wicked/ Posted by: Dave Taylor at July 24, 2007 6:04 AMThanks Justin, that short cut across comparing floating point numbers really helped me... doing that was such a torture.... however just for info is there an alternative way of doing it also ... ? Posted by: Samreen at August 28, 2007 10:09 AMI have a lot to say, but ...
I do have a comment, now that you mention it!
|
Search
Find just the answers you seek from among our 1700+ free tech support articles by using our Lijit search engine.
Help!
Subscribe to
Ask Dave Taylor!
Free Updates!
Sign up and get free weekly updates and special offers on books, seminars, workshops and more.
Articles and Reviews
Auctions and Online Shopping Blogs and RSS Feeds Building Web site traffic Business and Management Cell Phones and Mobile Phones CGI Scripts and Web Site Programming Computer and Internet Basics d) None of the Above HTML and CSS Mac OS X Help MySpace, Facebook, Twitter and Social Network Help Pay Per Click (PPC) Search Engine Optimization Shell Script Programming Sony PSP, MP3 Players, Etc. The Writing Business Unix and Linux Help Video Game Tips and Help Windows Help
Recent Entries
Join the List!
Book Links
|