Backup all apks from device using adb: why this loop in bash script doesn't work? You can do adb shell pm list packages, and after reading through the list, do an adb shell pm path "com.yourpackage" to get the full path and do a simply adb pull.

Fact is: I want to automate this. I thought about a really simple bash script:

for apk in $(adb shell pm list packages | sed 's/package://g' | sort); do
    # If you just do an echo, IT WORKS
    # echo $apk
    # But here it doesn't work
    adb shell pm path $apk
done


But that simply doesn't work. It seems that "$apk" becomes lost or something and nothing is shown in that snippet. I don't know if it's a subshell problem, or some peculiarity when using variables that got through an adb shell.

Should I create a script apks.sh just using pm list, for and such, push it to my device, run adb shell only once and execute apks.sh?
It doesn't work because adb  adds carriage return in the output. You can read Gilles' answer for more info on that.
All of you've to do is remove the carriage return. Here's the tweaked script of yours:

#!/bin/bash

for package in $(adb shell pm list packages | tr -d '\r' | sed 's/package://g'); do
    apk=$(adb shell pm path $package | tr -d '\r' | sed 's/package://g');
    echo "Pulling $apk";
    adb pull -p "$apk";
done

You can use -p with adb pull if only you've version 1.0.32 or above of adb. sort is not needed, as I see it.