abkrim
abkrim

Reputation: 3692

Escape single quotes ssh remote command

I read any solutions for escaping single quotes on a remote command over ssh. But any work fine.

I'm trying

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

AWK doesn't work:

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 I tried using single quotes on the command line, but they also didn't work.

Upvotes: 6

Views: 12651

Answers (2)

Ben
Ben

Reputation: 1670

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.

Upvotes: 9

Adrian Pronk
Adrian Pronk

Reputation: 13906

In your first try you use double-quotes " so you need to escape the $ character:

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

Also, you can use:

 ps uax | grep 'ba[c]' | ...

so then you don't need the grep -v grep step.

Upvotes: 8

Related Questions