sup*_*anh 15 string shell-script test numeric-data
我正在检查我的主题的更新脚本
我有 2 个文本文件。第一个称为“current.txt”并包含当前版本。4.1.1
该文本文件中有字符串。
第二个称为“latest.txt”并包含最新版本。4.2
此文本文件中有字符串。
所以这是代码
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
Run Code Online (Sandbox Code Playgroud)
这意味着如果 current.txt 与 latest.txt 不同,那么它会说“有 4.2 版更新”。如果不是,它会说“版本 4.1.1 是最新版本”
但是当我尝试运行它时。我收到这个错误
Checking update
./test.sh: line 4: [: 4.1.1: integer expression expected
Version 4.1.1 is the latest version
Run Code Online (Sandbox Code Playgroud)
那么我做错了什么?
Jef*_*ler 22
该test
命令也称为[
,具有用于字符串比较和整数比较的单独运算符:
整数 1 -eq 整数 2
INTEGER1 等于 INTEGER2
对比
字符串 1 = 字符串 2
字符串是相等的
和
字符串 1 != 字符串 2
字符串不相等
由于您的数据不是严格意义上的整数,您的测试需要使用字符串比较运算符。评论中的最后一个实现是“-eq”逻辑与 if/elseecho
语句的含义不匹配,因此新代码段应该是:
...
if [ "$x" != "$y" ]
then
echo There is version $y update
else
echo Version $x is the latest version
fi
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果您有两个版本字符串(例如 in$x
和$y
),您可以使用printf
和 GNUsort
来查找哪个版本较新。
$ 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
Run Code Online (Sandbox Code Playgroud)