Search code examples
bashescapingadbsu

How to escape a nested ADB shell command in bash


For a bash script that involves issuing a dconf command as user ceres via ADB shell, i need to nest multiple commands. Manual sequential execution of following three commands works flawless.

adb shell
su ceres
dconf write /desktop/asteroid/watchface "'file:///usr/share/asteroid-launcher/watchfaces/$opt.qml'"

I learned to escape the dconf keywords to correctly nest dconf in su ceres -c '<command>'.

su ceres -c 'dconf write /desktop/asteroid/watchface \"'file:///usr/share/asteroid-launcher/watchfaces/$opt.qml'\"'

How to nest and escape above command into adb shell "<command>"?

adb shell "su ceres -c 'dconf write /desktop/asteroid/watchface \"'file:///usr/share/asteroid-launcher/watchfaces/$opt.qml'\"'"

Results in dconf reply error: 0-4:unknown keyword when issued from the bash script.

Thank you for your help and explanation!


Solution

  • For extremely nested cases I'd stick to printf %q instead of doing the quoting manually:

    #! /usr/bin/env bash
    printf -v cmd %q "'file:///usr/share/asteroid-launcher/watchfaces/$opt.qml'"
    printf -v cmd %q "dconf write /desktop/asteroid/watchface $cmd"
    adb shell "su ceres -c $cmd"