5

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 

    2 Answers 2

    8

    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.

    3
    • Yeah, you are just having trouble with the shell expansion rules. Check the expansion man page
      – mateor
      CommentedJul 5, 2013 at 3:18
    • After try, I find that adb shell 'mkdir /xxx; echo $?' worked, but adb shell "mkdir /xxx; echo $?" not work, strange.CommentedFeb 24, 2021 at 6: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 adbCommentedFeb 24, 2021 at 19:41
    2

    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 
    2
    • 1
      In 2023 is it still impossible to natively get the exit status of the command from adb shell?
      – pmor
      CommentedNov 21, 2023 at 14:59
    • adb shell is not an emulator. And which version of adb are you referring to?
      – phuclv
      CommentedMar 15, 2024 at 11:32

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.