Just found out how to fix the problem so here is the guide:
How to troubleshoot commands that wont execute properly from within a script
aka
How to view exactly what is being executed by the shell
In the script, enclose your problematic command with the set command:
set -x #unhide debug info
your command
set +x #hide debug info
In my previous example, were port=1000 and cmd="ls /dev/shm":
ssh [email protected] -p $port "'"$cmd"'"
Was actually sent to the shell and executed as:
ssh [email protected] -p 1000 ''\''ls' '/dev/shm'\'''
Look at that! Now we all know, double quotes " " are in fact an hyperactive bipolar single quote in disguise just waiting around the corner to mess with you... and sometimes it brings a friend called Mr. backslash.
The solution was to use double quotes in the script:
ssh [email protected] -p $port "$cmd"
When combined with the double quotes from the command line the quoting get translated and executed as single quotes ' ' like this:
ssh [email protected] -p 1000 'ls /dev/shm'
Who knew! you did? good for you!
Just another way nix messes with us :P