I'm starting to learn about writing scripts for the bash terminal, but I can't work out how to get the comparisons to work properly. The script I'm using is:
echo "enter two numbers";
read a b;
echo "a=$a";
echo "b=$b";
if [ $a \> $b ];
then
echo "a is greater than b";
else
echo "b is greater than a";
fi;
The problem I have is that it compares the number from the first digit on, i.e. 9 is bigger than 10000, but 1 is greater than 09
How can I convert the numbers into a type to do a true comparison?
In Bash I prefer doing this as it addresses itself more as a conditional operation unlike using
(( ))
which is more of arithmetic.Unless I do complex stuffs like
But everyone just has their own preferences. Sad thing is that some people impose their unofficial standards.
Update:
You actually can also do this:
Which allows you to add something else which you could do with
[[ ]]
besides arithmetic stuffs.I solved this by using a small function to convert version strings to plain integer values that can be compared:
This makes two important assumptions:
For example
Example testing whether
npm
command meets minimum requirement ...There is also one nice thing some people might not know about:
This code will print the smallest number out of
a
andb
In bash, you should do your check in arithmetic context:
For POSIX shells that don't support
(())
, you can use-lt
and-gt
.You can get a full list of comparison operators with
help test
.This code can also compare floats. It is using awk (it is not pure bash), however this shouldn't be a problem, as awk is a standard POSIX command that is most likely shipped by default with your operating system.
To make it shorter for use, use this function:
Plain and simple
You can check out this cheatsheet if you want more number comparsions in the wonderful world of Bash Scripting.
Shortly, integers can only be compared with: