Bash 如何检查变量是否在范围内


if [[ $entriestoDisp == [^1-9] ]]; then 
     echo "Invalid number of entries, choose between 1 to 9."
else
     #displays logs

您好,我在使用这段特定的代码时遇到了问题。我想在继续之前验证变量条目到Disp的值是否在1到9之间。我做错了什么?

不要使用正则表达式进行范围检查,除非您希望在继续之前验证entriesToDisp确实是整数。只需使用常规比较运算符。

if ! [[ $entriesToDisp =~ [[:digit:]]+ ]]; then
    echo "$entriesToDisp is not an integer"
elif ! (( 1 <= $entriesToDisp && $entriesToDisp <= 9 )); then
    echo "$entriesToDisp not in range 1-9"
fi

无论涉及多少位数字,这都将起作用。

你非常接近:

if [[ ! $entriestoDisp = [1-9] ]]; then 
  echo ouch
fi

最新更新