Ifechi
Ifechi

Reputation: 117

Escape awk command in ssh

I have the following command;

su user1 -c "ssh [email protected] awk '$5\==1{print\$3}' filename.log" | uniq -c

Running the command gives the error:

awk: ==1{print
awk: ^ syntax error
awk: cmd. line:1: ==1{print
awk: cmd. line:1:          ^ unexpected newline or end of string

I have tried several escaping methods with no luck. Any advice will be deeply appreciated. Thanks.

Upvotes: 2

Views: 1019

Answers (2)

fedorqui
fedorqui

Reputation: 289915

I would go for this:

su user1 -c "ssh [email protected] \"awk '\\\$5==1{print \\\$3}' filename.log\"" | uniq -c
                                   ^^                                    ^^

Basically, first of all you need to imagine how to execute the command if you are user1:

ssh [email protected] "awk '\\\$5==1{print \\\$3}' filename.log"

and then you introduce it into the su user1 ... escaping the quotes.

Upvotes: 2

janos
janos

Reputation: 124664

Escaping the right way is quite tricky. You could write like this:

su user1 -c 'ssh [email protected] awk \"\\\$5 == 1 {print \\\$3}\" filename.log' | uniq -c

or like this:

su user1 -c "ssh [email protected] awk \'\\\$5 == 1 {print \\\$3}\' filename.log" | uniq -c

That is, you need to escape the quotes and the $ signs within the quoted string. Since the $ signs always need to be escaped, you need to double-escape it in this case, that's why the \\\.

Upvotes: 1

Related Questions