Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I regularly record audio files using my Android phone to WAV files to the internal storage of my phone. I'd like to write a Bash script to pull the most recent recorded file from my phone and move it to my Desktop. Here's what I've got so far:

adb shell find /storage/sdcard0/Sound\ Recordings/ | tail -1 | while read file ; do
    adb pull "$file" ~/Desktop/

However, this fails. It seems that ADB doesn't properly escape things and I get the following messages when trying to run the script:

' does not existstorage/sdcard0/Sound Recordings/20120817T065953.wav

It seems to ignore the double quotes and everything basically breaks when it tries to run, as it presumably sees 3 arguments rather than two, something like this:

adb pull /storage/sdcard0/Sound Recordings/20120817T065953.wav ~/Desktop/

How can I adjust my script to insert backslashes into my $file variable where necessary? Is that the proper solution in this case?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

Since you're running this in another shell level, it gets expanded before it's run in the subshell. The easiest way to fix this is to escape any special characters in the file name:

adb shell find /storage/sdcard0/Sound\ Recordings/ | tail -1 | while IFS= read -r file ; do
    adb pull "$(printf %q "$file")" ~/Desktop/
share|improve this answer
This is now giving me the following error: remote object '/storage/sdcard0/Sound$'Recordings/20120831T070055.wav\r'' does not exist. Somehow, it's formatting the filename in a very strange way. –  Naftuli Tzvi Kay Sep 3 '12 at 15:07
$file needs to be quoted in the printf command. Also, change while read file to while IFS= read -r file to read the whole line. Or better, just do: file=$(adb shell find /blah | tail -1); adb pull "$(printf %q "$file")". –  dubiousjim Oct 3 '12 at 14:19
@dubiousjim Good tips. I'd normally include them in the first revision, except that it's pretty much in the middle of a spectrum of robustness for file loops. –  l0b0 Oct 3 '12 at 14:44
add comment

This is the solution:

adb pull "/storage/sdcard0/Sound Recordings/$(
    adb shell ls -1t '/storage/sdcard0/Sound Recordings' |
        sed q |
        tr -d '\r'
)" .

You are facing problems because adb return some carriage returns like Windows \r

sed q is just a funny way to display the first occurrence like head -n1

share|improve this answer
Have you tested ? –  sputnick Oct 3 '12 at 15:19
thanks for the tr -d '\r' –  uval Jun 26 '13 at 20:33
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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