adb shell su -c is a commonly used adb command. Normally you just need to append arguments to the command line like this:

adb shell su -c echo ab

However, things can be tricky if you want to add quotes. For example, to print a b (there are 2 spaces), these won't work:

adb shell su -c echo "a  b"
adb shell su -c "echo \"a  b\""
adb shell su -c "echo 'a  b'"

You have to use these:

adb shell su -c "\"echo \\\"a  b\\\"\""
adb shell "su -c \"echo \\\"a  b\\\"\""
adb shell su -c "\"echo 'a  b'\""
adb shell "su -c \"echo 'a  b'\""

I'd like to know which is the standard way of writing such a command. Standard means it handles quotes correctly and in the most straightforward way.

My current research:

  • adb handles command arguments the same way as ssh: Arguments are connected (with space) into a string, and that string is executed.

  • su -c expects a single string as the command line, and it doesn't do the concatenation for you.

So I think the most standard way of writing adb shell su -c should be like:

adb shell "su -c \"echo \\\"a  b\\\"\""

However, I'm not very confident about this. Does anyone have concrete reference confirming what I'm doing or showing I'm doing it wrong?

  • When I get in this kind of situation I do: adb shell 'su -c "echo a\ \ b"'. I use single quotes to enclose everything after adb shell and double quotes inside, wherever needed. – Firelord Sep 17 '18 at 14:23

The best solution would be to use single-quotes (') around the subcommand:

adb shell 'su -c echo "a  b"'

But please note that usually within single-quotes everything is taken literally and variables are not expanded. This doesn't apply when you nest quotes like this. As an example:

echo "$myvar"   # prints 123
echo '$myvar'   # prints $myvar

But: (assuming $myvar is set to '123' within the adb shell (e.g. on phone))

adb shell 'su -c echo "$myvar"'    # prints 123

In case you want to use your own shell variables to be included within the adb subcommand, you can simply flip around the quotes:

adb shell "su -c echo '$myvar'"    # prints test

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.