5

I want to execute the awk command with long parameters,like this:

ssh host "netstat -rn|awk 'NR!=1 && NF>=6 && $1!="Destination" {printf "%-15s %-20s\n", $1, $2}'|sort -f "

but there are some errors:

syntax error The source line is 1. The error context is NR!=1 && NF>=6 && >>> != <<< awk: Quitting The source line is 1.

So,how can I fix it?

1
  • 2
    For this particular case, you don't need to escape the awk script through ssh; you could run only the netstat remote, and pipe ssh's output to local awk which is easier to get right (and sort). Commented Apr 13, 2014 at 16:33

2 Answers 2

14

use here-docs to get around all of the nasty subshell quoting:

ssh you@host <<-\SSH
    awk -f 3<<\AWK /dev/fd/3
        awk script
        as many lines as you like
        "$vars and quotes" are only evaluated by awk
    #END
    AWK
    "$vars and quotes" are only evaluated by remote shell
    echo 'single quotes and all'
    rest of ssh script
#END
SSH
5
  • Thanks mikeserv! You inspired me,I use this: ssh you@host <<EOF netstat -rn|awk 'NR!=1 && NF>=6 && $1!="Destination" {printf "%-15s %-20s\n", $1, $2}'|sort -f \nEOF
    – CatWin
    Commented Apr 14, 2014 at 5:17
  • @Catwin you use what?
    – mikeserv
    Commented Apr 14, 2014 at 5:18
  • Why is there a backslash on \SSH and \AWK Commented Oct 21, 2015 at 17:42
  • 5
    @javadba Backslash disables variable escaping inside the heredoc. The - trims away leading tab characters (but not spaces) inside the heredoc. See tldp.org/LDP/abs/html/here-docs.html
    – Alicia
    Commented May 8, 2016 at 11:43
  • Escaping a command is better idea, terminals may not be configured to allow redirection via input stream, this answer is much less flexible. I'm yet to see the production environment where that would be allowed.
    – nethero
    Commented Feb 4, 2021 at 13:54
9

Use backslashes to protect $ and " inside the remote command:

ssh host "netstat -rn|awk 'NR!=1 && NF>=6 && \$1!=\"Destination\" {printf \"%-15s %-20s\n\", \$1, \$2}'|sort -f "
1
  • 1
    This is better answer as it is not depending on the host configuration, some servers may not accept the input from heredoc.
    – nethero
    Commented Feb 4, 2021 at 13:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .