比较 Bash shell 中的整数变量

Comparing an integer variable in the Bash shell

我知道我遗漏了一些非常明显的东西,但我就是看不到它。在下面的代码中,new_i 变量正确递增,但是,当我到达 if 语句时,我认为我的语法已关闭。我查看了一些示例,但是当 if 语句大于(在本例中为 15)一个数字时,none 显示变量设置为零。

#!/bin/sh
i=$(cat /etc/hour.conf)
new_i=$((i+1))
if [[ "$new_i" -gt 15 ]]; then
 new_i=0
fi
echo "$new_i">/etc/hour.conf
echo "$new_i"

当我 运行 这个脚本时,我得到以下错误:

./loops: 3: ./loops: Illegal number: new_i

在此先感谢您的帮助!

不加引号试试:

if [ $new_i -gt 15 ]; then
    ...
fi

或者,更好的是,使用算术评估

if (( $new_i > 15 )) ; then
    ...
fi

这行得通 - new_i=$(( 行中 i 前面的 $ 以及引号和一组括号的删除修复了错误,现在脚本可以按预期工作。感谢大家的帮助!

#!/bin/sh
i=$(cat /etc/hour.conf)
new_i=$(($i+1))
if [ $new_i -gt 15 ]; then
 new_i=0
fi
echo "$new_i">/etc/hour.conf
echo "$new_i"