4

How should I get $? of adb shell <command>?

I would like to check the result of adb shell mkdir /xxx.

I executed mkdir command by adb shell and failed but the result of $? is 0.

$ adb shell mkdir /xxx
mkdir failed for /xxx, Read-only file system
$ adb shell echo $?
0

$ adb shell "mkdir /xxx; echo $?"
mkdir failed for /xxx, Read-only file system
0

I would like to get the result code of adb shell <command> but not in the interactive mode like below:

$ adb shell
shell@android:/ $ mkdir /xxx
mkdir failed for /xxx, Read-only file system
255|shell@android:/ $ echo $?
255
Alex P.
  • 30,437
  • 17
  • 118
  • 169
Sea Mountain
  • 369
  • 1
  • 4
  • 11

2 Answers2

6

You should do:

$ adb shell 'mkdir /xxx; echo $?'
mkdir failed for /xxx, Read-only file system
255

Notice the single quotes, otherwise $? is evaluated before reaching adb.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • Yeah, you are just having trouble with the shell expansion rules. Check the [expansion man page](http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) – mateor Jul 05 '13 at 03:18
  • After try, I find that `adb shell 'mkdir /xxx; echo $?'` worked, but `adb shell "mkdir /xxx; echo $?"` not work, strange. – user3875388 Feb 24 '21 at 06:44
  • Not strange at all, try `$ echo adb shell "mkdir /xxx; echo $?" adb shell mkdir /xxx; echo 0`, (check the `0`); the double quotes allow the expansion of `$?` before invoking `adb` – Diego Torres Milano Feb 24 '21 at 19:41
1

If you are using an older emulator, then adb shell does not return the exit value. Then you have to use adb shell 'false; echo $?' like in https://stackoverflow.com/a/17480194/306864

In newer emulators, it works properly, then you can do adb shell false || echo failed. Here's how I tested:

$ adb -e android-22 shell false; echo $?
0
$ adb -e android-22 shell 'false; echo $?'
1
$ adb -e android-29 shell false; echo $?
1
$ adb -e android-29 shell 'false; echo $?'
1