Marco Couto Marco Couto - 6 months ago 17
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

adb
. 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
/sdcard
, 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:

newDir=$folder/testResults


The problem is that the
newDir
variable was allways having the value
/testResults
, ignoring the value of
folder
.

At first, I thought that it might be a subshell problem, i.e. the value of
folder
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
folder
with a smaller string than
folder
('pop', for instance), like this:

newDir=$folder/pop


This is the result when I run
echo $newDir
:

/popard


CONCLUSION: For some reason, the value of
folder
is being "ignored", and when it tries to concat with other string
s
it will actually replace the first
N
characters of
folder
(with
N=length(s)
).

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

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


And the result is this:

/poprd


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"
newDir=$folder/testResults
echo $newDir


The result is correct:
/sdcard/testResults


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)
newDir=$folder/pop
echo $newDir


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

folder=$(cat result.txt)
newDir=$folder/pop
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

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

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