I am making the check for update script for my theme
I have 2 text files. First one is called “current.txt” and contains the current version. There is 4.1.1 string in that text file.
Second one is called “latest.txt” and contains the latest version. There is 4.2 string in this text file.
So here is the code
echo "Checking update";
x=$(cat ./current.txt)
y=$(cat ./latest.txt)
if [ "$x" -eq "$y" ]
then
echo There is version $y update
else
echo Version $x is the latest version
fi
What it mean is if current.txt is NOT the same with latest.txt then it will say “there is version 4.2 update”. If not, it will say “version 4.1.1 is the latest version”
But when I try to run it. I get this error
Checking update ./test.sh: line 4: [: 4.1.1: integer expression expected Version 4.1.1 is the latest version
So what am I doing wrong with this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The test command, also named [, has separate operators for string comparisons and integer comparisons:
INTEGER1 -eq INTEGER2
INTEGER1 is equal to INTEGER2
vs
STRING1 = STRING2
the strings are equal
and
STRING1 != STRING2
the strings are not equal
Since your data is not strictly an integer, your test needs to use the string comparison operator. The last realization in the comments was that the “-eq” logic did not match the sense of the if/else echo statements, so the new snippet should be:
...
if [ "$x" != "$y" ]
then
echo There is version $y update
else
echo Version $x is the latest version
fi
Method 2
BTW, if you have two version strings (e.g. in $x and $y) you can use printf and GNU sort to find which is newer.
$ x=4.1.1
$ y=4.2.2
$ printf "%sn" "$x" "$y" | sort -V -r
4.2.2
4.1.1
$ if [ $(printf "%sn" "$x" "$y" | sort -V -r | head -1) = "$x" ] ; then
if [ "$x" = "$y" ] ; then
echo "$x is equal to $y"
else
echo "$x is newer than $y"
fi
else
echo "$x is older than $y"
fi
4.1.1 is older than 4.2.2
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0