Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape single quotes ssh remote command

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

like image 412
abkrim Avatar asked Mar 22 '13 10:03

abkrim


People also ask

How do I SSH to a remote host?

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.

How to run multi-line commands with SSH?

This post will cover three different methods to remotely execute multi-line commands with SSH. To run the third, fourth, fifth, etc. commands on a remote server with SSH, keep appending commands with a semicolon inside the single quotes.

How does the ssh command work in Linux?

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.

How to escape the dollar sign in bash script?

Since you won't be using quotes, all special bash characters need to be escaped with backslashes. or you could double quote the single quotes instead of escaping them (in both cases, you need to escape the dollar sign)


1 Answers

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.

like image 58
Ben Avatar answered Nov 15 '22 06:11

Ben