apricot
apricot

Reputation: 3747

Bash conditional expression not working

$ echo $(adb shell getprop service.adb.root)
1
$ while [[ $(adb shell getprop service.adb.root) != "1" ]]; do echo -n .; done
.........^C

[[ "1" != "1" ]] should be false and the while loop should not run. But, it runs forever. What's the reason and the fix?

I am trying to write a loop that will wait until the adbd daemon on the connected Android device restarts as root.

Upvotes: 1

Views: 424

Answers (2)

anubhava
anubhava

Reputation: 785186

Since output of adb command has trailing \r you can use this while loop instead:

while [[ $(adb shell getprop service.adb.root) != $'1\r' ]]; do echo -n .; done

i.e. compare numbers not strings.

Upvotes: 3

larsks
larsks

Reputation: 311625

The result from the getprop command contains a carriage return (ASCII 0x0d). Since you're making a string -- not a numeric -- comparison, you're effectively running:

[[ "1" != "1\r" ]]

The simplist way to fix this is to explicitly strip the carriage return:

x=$(adb shell getprop  service.adb.root | tr -d '\015')

Now your comparison should work.

You can see exactly what getprop is returning by running:

$ adb shell getprop  service.adb.root | od -c
0000000   1  \r  \n
0000003

Upvotes: 3

Related Questions