字符串到浮动比较在shell脚本中不起作用
REQUIRED_VERSION=2.38.0
VERSION=$(echo $FULL_DATA | cut -d ":" -f 5) #This gives values as 2.10.0 OR 2.40
if [ $VERSION -gt $REQUIRED_VERSION ]]
then
echo "=== PASSED ==== "
else
echo "=== FAILED ==="
#exit 1
fi
字符串
使用zsh得到如下错误
test.sh:60:错误的浮点常量
它总是给出带有sh的结果
我也试过bc,但不起作用,可能缺少语法,不确定。
请建议一些方法来从字符串类型转换为浮点数,我可以与shell或zsh进行进一步比较
4条答案
按热度按时间kx7yvsdv1#
版本号不是数学数字。Bash没有内置的方法来比较版本号。
sort
命令有-V
用于比较版本号,-C
用于报告文件是否正确排序。您可以将其与Bash的<<<
功能一起使用,以将即时输入传递给命令:字符串
$'\n'
语法是一个用于生成换行符的Bash特性。Bash允许你在命令前用
!
否定测试:型
请注意,
sort
将报告“2.38”早于“2.38.0”。8tntrjer2#
您不能将版本作为任何类型的数字(包括浮点数)进行比较,也不能将版本作为字符串进行比较,因为每个
.
分隔的部分都需要单独进行数字比较。您需要将它们具体作为版本进行比较,例如:使用GNU sort for-V
将版本号列表按从低到高的顺序排序:字符串
型
如果你没有GNU
sort
,你可以编写自己的比较函数,例如:型
型
hmtdttj43#
这可以在纯bash中完成,但当然它需要更多的代码:
字符串
此输出
型
6tqwzwtp4#
zsh
附带了一个比较版本号的函数:字符串
它可以接受点或破折号作为分隔符,看起来它也可以处理字母:
型