Backup all apks from device using adb: why this loop in bash script doesn't work?
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.