Here我找到了很好的解决方案来测试变量是否为数字:

case $string in
   ''|*[!0-9]*) echo bad ;;
   *) echo good ;;
esac

我试图修改它来测试变量是否是1、2、3或4位数的自然数(在0-9999范围内),所以我添加了|*[0-9]{5,}*来排除大于5位数的数字,但下面的代码打印大于9999的数字,例如1234567。
case $string in
   ''|*[!0-9]*|*[0-9]{5,}*) echo bad ;;
   *) echo good ;;
esac

我在用垃圾箱里的灰。

最佳答案

不确定您是否需要在case语句中使用此选项,因为我只想:

if { test "$string" -ge 0 && test "$string" -lt 10000; } 2> /dev/null; then
  echo good
else
  echo bad
fi

如果要在严格可移植的shell中使用case语句,可能会遇到以下问题:
case $string in
    [0-9]|[0-9][0-9]|[0-9][0-9][0-9]|[0-9][0-9][0-9][0-9]) echo good;;
     *) echo bad;;
esac

08-04 16:37