简体   繁体   中英

Shell script works in bash but not on 'adb shell'

Below shell script works perfectly fine in bash shell. But produces an error in android shell. May be it has got to do something with the shell that android is using. But how can I resolve it? If not a perfect solution, an hack would also do for me.

Shell-script :

func()
{
    local x
    x=${1:3:1}
    echo "x - $x"
    if [ "${x}" = " " -o -z "${x}" ]; then
      a="M"
    else
      a="S"
    fi
    echo "A - ${a} X - {x}"
}

func "abc=efg"

O/p In android shell,

root:/ # sample.sh                                                  
x - =
/system/bin/sample.sh[14]: [: =: missing second argument
A - S X - {x}

O/p on bash shell(Linux):

PC:~$ ./sample.sh 
x - =
A - S X - {x}

When the value of $x is just = , it looks like:

if [ = = " " -o -z = ]; then

and it's apparently getting confused by the = that should be a value rather than an operator.

Change it to:

if [ "x${x}" = "x " -o "x${x}" = "x" ]; then

The adb shell was a direct descendant of BSD ash, of which dash is also. The adb shell in more recent android versions is mksh standard shell of non-emulator builds on Android 4.0 and newer .

From the error text it is probable that the shell is some mksh version.

As the mksh in android is under heavy changes and improvements, I recommend you to take dash as the target shell. It is available in most linux distributions and is the default system shell for debian and derivatives. It has less features but it is very difficult that something that work in dash will not work in the mksh of adb.

{1:3:1}

In particular, this expression:

x=${1:3:1}

has no meaning in dash (it does work, however, in mksh). It could be replaced with this:

x=${1#???}; x=${x%"${x#?}"}

A bit longer, but gets the job done in any shell.

[

Also, there is a problem with the […] test, it seems to have too many "parts" to be reliable. Dividing the test into two (or more if needed) is the usual remedy:

if [ "${x}" = " " ] || [ -z "${x}" ]; then

The || is also an or (with the same preference as && , the and).
Which also works in any shell.

With a final change of (a missing $ for variable x):

 echo "A - ${a} X - ${x}"

We get the whole script as:

func()
{
    local x
    x=${1#???}; x=${x%${x#?}}
    echo "x - $x"
    if [ "${x}" = " " ] || [ -z "${x}" ]; then
      a="M"
    else
      a="S"
    fi
    echo "A - ${a} X - ${x}"
}

func "abc=efg"

And running it in dash, bash or mksh, gives:

x - =
A - S X - =

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM