Search code examples
bashadb

ADB command doesn't read bash variable and returns empty line


I'm currently working on a BASH script to get the path of all apps through ADB in order to pull it afterwards. I get an empty line as the result of the last echo.

If I write a package name directly instead if $pkg, il works. Looks like the $pkg variable is not well "digested" by adb shell pm path

for line in $(adb shell pm list packages -3)
do
    line=$line | tr -d '\r'
    pkg=${line:8}
    path=$(adb shell pm path $pkg | tr -d '\r')
    echo $path
done

Solution

  • Your attempt to strip the carriage return from line is incorrect; as a result, pkg still ends with a carriage return. You need to write

    line=$(echo "$line" | tr -d '\r')
    

    However, a simpler method is to use parameter expansion instead:

    line=${line%$'\r'}
    

    Further, you shouldn't use a for loop to iterate over the output of a command. Use a while loop with read instead:

    while IFS= read line; do
        line=${line%$'\r'}
        pkg=${line:8}
        path=$(adb shell pm path "$pkg" | tr -d '\r')
        echo "$path"
    done