Escape single quotes ssh remote command

abkrim picture abkrim · Mar 22, 2013 · Viewed 11k times · Source

I read any solutions for escape single quotes on remote command over ssh. But any work fien.

I'm trying

ssh root@server "ps uax|grep bac | grep -v grep | awk '{ print $2 }' > /tmp/back.tmp"

Don't work awk

ssh root@server "ps uax|grep bac | grep -v grep | awk \'{ print $2 }\' > /tmp/back.tmp"
....
awk: '{
awk: ^ caracter ''' inválido en la expresión

And try put single quotas on command but also don't work.

Aprecite help

Answer

Ben picture Ben · Dec 3, 2013

The ssh command treats all text typed after the hostname as the remote command to executed. Critically what this means to your question is that you do not need to quote the entire command as you have done. Rather, you can just send through the command as you would type it as if you were on the remote system itself.

This simplifies dealing with quoting issues, since it reduces the number of quotes that you need to use. Since you won't be using quotes, all special bash characters need to be escaped with backslashes.

In your situation, you need to type,

ssh root@server ps uax \| grep ba[c] \| \'{ print \$2 }\' \> /tmp/back.tmp

or you could double quote the single quotes instead of escaping them (in both cases, you need to escape the dollar sign)

ssh root@server ps uax \| grep ba[c] \| "'{ print \$2 }'" \> /tmp/back.tmp

Honestly this feels a little more complicated, but I have found this knowledge pretty valuable when dealing with sending commands to remote systems that involve more complex use of quotes.