3

I have this script:

port=$1
cmd=$2
ssh root@127.0.0.1 -p $port "'"$cmd"'"

When running myscript.sh 1000 "ls /dev/shm" it get this error:

bash: ls /dev/shm: No such file or directory

In the script, if I echo the command (to see how it's evaluated) like this:

echo ssh root@127.0.0.1 -p $port "'"$cmd"'"

I get this:

echo ssh root@127.0.0.1 -p $port "'"$cmd"'"

Which is the proper command... So what is it that I am missing here?

Thank you.

4

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 root@127.0.0.1 -p $port "'"$cmd"'"

Was actually sent to the shell and executed as:

ssh root@127.0.0.1 -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 root@127.0.0.1 -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 root@127.0.0.1 -p 1000 'ls /dev/shm'    

Who knew! you did? good for you!

Just another way nix messes with us :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.