6

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?

9

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
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 "%s\n" "$x" "$y" | sort -V -r
4.2.2
4.1.1

$ if [ $(printf "%s\n" "$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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.