0

First, sorry if my question is obscure or in an inconvenient format. This is my first post here :D.

My issue is that I have a script, let's say test.sh which reads an input, and validates if it's a positive integer (reg ex used from this post: 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

I am running this script on my android device (Xiaomi Mi3 w) using adb shell and the error: syntax error: =~ unexpected operator keeps displaying.

First, is my regex even correct? Second, any hints on how I can overcome this syntax error?

Community
  • 1
  • 1
t4kmode
  • 1
  • 4

3 Answers3

1

The default shell in Android is mksh. It is not 100% compatible with bash. So do not expect all bash recipes to work without changes.

For the description of features supported by mksh - read its manual page.

Alex P.
  • 30,437
  • 17
  • 118
  • 169
  • I tried using the manual, and I tried a few things but doesn't work. So far, the closest I got was : if [ $num -gt 0].... but this will accept values sch as '-123' or '444a'. Any ideas? I tried using expressions such as $num -eq +[0-9] which I read in the manual, but it had worse results. – t4kmode Jul 04 '15 at 03:12
1

This is a GNU bash POSIX regular expression. In Korn Shell, you can use extglob regular expressions to the same effect:

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

See the section “File name patterns” in the manpage for details.

mirabilos
  • 5,123
  • 2
  • 46
  • 72
0

I had to use ksh expression as shown below to get this to work.

case $num in
    +([0-9])*(.)*([0-9]) )
          # Variable positive integer
      echo "positive integer"
          ;;
    *) 
          # Not a positive integer
      echo "NOPE"
      exit
          ;;
esac
Barmar
  • 741,623
  • 53
  • 500
  • 612
t4kmode
  • 1
  • 4