Marco Couto Marco Couto - 2 years ago 78
Bash Question

ADB - Getting string from the device using adb shell has unexpected and weird behavior

I am having the weirdest problem when I try to concat 2 String in a shell script.

First, let me tell you what I want to do.
I want to create a folder in the external storage of an Android device, using

. In order to do that, I first need to get the external storage folder of the device.

For that, I used this:

folder=$(adb shell 'echo $EXTERNAL_STORAGE')

And it works, since if I try to run
echo $folder
the result is
, which is the correct external storage folder.

But I want to create a new folder inside it, called testResults. So, to get the full path I tried this:


The problem is that the
variable was allways having the value
, ignoring the value of

At first, I thought that it might be a subshell problem, i.e. the value of
was not available when I tried to concat it with the new String "for some reason". But then, it got even weirder...

If I try to concat
with a smaller string than
('pop', for instance), like this:


This is the result when I run
echo $newDir


CONCLUSION: For some reason, the value of
is being "ignored", and when it tries to concat with other string
it will actually replace the first
characters of

I thought that maybe the
at the beginnig of
was the reason behind so much confusion, so I tried this:

folder=$(adb shell 'echo sdcard')
echo $newDir

And the result is this:


CONSLUSION: Something in the adb shell tool is making the strings behave anomalously.

In fact, the problem seems to be related with adb, because if I try this:

folder=$(echo "/sdcard") #or even folder="/sdcard"
echo $newDir

The result is correct:

But this gets even weirder...
I tried using files to help me, like this:

adb shell 'echo $EXTERNAL_STORAGE' > result.txt
folder=$(cat result.txt)
echo $newDir

The result here is
If I open the file, and insert something in the line that has the string
, to make it (for example)
, and then do this:

folder=$(cat result.txt)
echo $newDir

The result is: /popardish
If I remove that line in the file and then add another one, it works fine.

I seriously don't know what is happening...
Does anybody know what can possibly be happening?

Thanks in advance!

Answer Source

I'd guess there is a newline at the end of the folder value. Try this:

folder=$(adb shell 'echo -n $EXTERNAL_STORAGE')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download