busybox 是可变的数字?

busybox is variable a number?

以下脚本在我的 Ubuntu 16.04 shell:

上按预期工作
Teststring="1234a5"
re='^[0-9]+$'
if ! [[ $TestString =~ $re ]]; then
  echo "is not a number"
  exit 1
fi

虽然在我的目标上,我只有 busybox 而不是一个完整的 shell 并且它引发了以下错误:

ash: =~: unknown operand

如何让它与 busybox 一起工作?

背景:我有一个 busybox 脚本,它想从系统上的一个特殊文件中读取一个数字,用它做一些计算并将结果写到另一个文件中。 在 运行 进入 "not a number" 之前-错误之后,我想先做一个适当的检查。

  • 使用外部工具

egrep

if ! echo "$Teststring" | egrep -q "$re"; then

或修改re

re='[0-9]\+'
if ! expr "$Teststring" : "$re"; then
  • 使用内置 shell 扩展

在这种特殊情况下:如果字符串为空或包含非数字

case $Teststring in
    ''|*[!0-9]*) 
    echo "is not a number"     
    ;;
esac