adb shell 正则表达式在本地测试时不起作用

adb shell regular expression doesn't work as tested locally

首先,如果我的问题含糊不清或格式不便,请见谅。这是我第一次 post :D.

我的问题是我有一个脚本,比方说 test.sh,它读取一个输入,并验证它是否为正整数(此 post 中使用的 reg ex: BASH: Test whether string is valid as an integer?):

#!/bin/sh
echo -n " enter number <"
read num

if [[ $num =~ ^-?[0-9]+$ ]]     #if num contains any symbols/letters 
then                            # anywhere in the string
  echo "not a positive int"
  exit
else
  echo "positive int read"
fi

我 运行 在我的 android 设备(小米 Mi3 w)上使用 adb shell 这个脚本和错误: 语法错误:=~ unexpected operator 不断显示。

首先,我的正则表达式是否正确? 其次,关于如何克服此语法错误的任何提示?

Android 中的默认 shell 是 mksh。它不是 100% 兼容 bash。所以不要指望所有 bash 食谱都可以不做任何更改。

有关 mksh 支持的功能的描述 - 阅读其 manual page

我必须使用如下所示的 ksh 表达式才能使其正常工作。

case $num in
    +([0-9])*(.)*([0-9]) )
          # Variable positive integer
      echo "positive integer"
          ;;
    *) 
          # Not a positive integer
      echo "NOPE"
      exit
          ;;
esac

这是一个 GNU bash POSIX 正则表达式。在 Korn Shell 中,您可以使用 extglob 正则表达式达到相同的效果:

if [[ $num = ?(-)+([0-9]) ]]; then
    …

有关详细信息,请参阅联机帮助页中的“文件名模式”部分。