Logan Pickup Logan Pickup - 4 years ago 491
Bash Question

Copying files in ADB shell with run-as

Is there a way to write a script that will copy files from an ADB shell using run-as?

The only way I know of to copy in the adb shell is using

cat source > dest
, but I am only able to quote the greater-than sign one level deep - so my script can pass it to adb shell, but not to adb shell run-as.

For example, this works:

adb shell "cat source > dest"


But this does not:

adb shell run-as "cat source > dest"


Nor this:

adb shell "run-as cat source \> dest"


I even tried created a small script and uploading it to the device, but I can't seem to run the script from the adb shell - it tells me "permission denied". I can't chmod the script, either.

The reason I want to do this is to copy a file into an app's private storage area - specifically, I am using a script to modify shared preferences and put the modified preferences back. Only the app itself or root can write to the file I want, however.

Answer Source

Following Chris Stratton's advice, the way I eventually got this to work was as follows (for copying shared preferences back to the device):

adb push shared_prefs.xml /sdcard/temp_prefs.xml
cat <<EOF | adb shell
run-as com.example.app
cat /sdcard/temp_prefs.xml > /data/data/com.example.app/shared_prefs/com.example.app_preferences.xml
exit
exit
EOF

Piping directly to adb shell run-as did not work, and I do not know why, but piping to adb shell does. The trick is to then call run-as from the interactive shell, and it continues to accept input from the pipe.

The HERE doc lets me easily embed the newlines to separate commands and in general just makes it readable; I did not have much luck with semicolons, but that might have been because of the way I was doing things. I believe it might work with other methods of piping multiple commands/newlines; I stopped the experiment once I finally got it to work.

The two exits are necessary to prevent a hanging shell (killable with CTRL-C); one for run-as, and the other for adb shell itself. Adb's shell doesn't respond to end-of-file very nicely, it seems.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download