6

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
abkrim
  • 3,512
  • 7
  • 43
  • 69
  • Related: *[How to escape single quotes within single quoted strings](https://stackoverflow.com/questions/1250079/)* – Peter Mortensen Aug 16 '23 at 18:37
  • Possible canonical: *[How to escape the single quote character in an ssh / remote Bash command](https://stackoverflow.com/questions/20498599/how-to-escape-the-single-quote-character-in-an-ssh-remote-bash-command)* – Peter Mortensen Aug 16 '23 at 19:16
  • (Spanish: *[carácter](https://en.wiktionary.org/wiki/car%C3%A1cter#Noun_3)* - though it is missing the "á" here.) – Peter Mortensen Aug 16 '23 at 19:16

2 Answers2

9

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.

Ben
  • 1,620
  • 18
  • 11
8

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.

Adrian Pronk
  • 13,486
  • 7
  • 36
  • 60