关于使用 SSH 管道转义

Cat*_*Win 4 shell bash ssh quoting

我想用长参数执行 awk 命令,如下所示:

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

但有一些错误:

语法错误 源代码行是 1。错误上下文是 NR!=1 && NF>=6 && >>> != <<< awk: Quitting 源代码行是 1。

那么,我该如何解决呢?

mik*_*erv 14

使用 here-docs 绕过所有讨厌的 subshel​​l 引用:

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
Run Code Online (Sandbox Code Playgroud)

  • @javadba 反斜杠禁用 heredoc 中的变量转义。`-` 删除了heredoc 中的前导制表符(但不是空格)。见 http://www.tldp.org/LDP/abs/html/here-docs.html (5认同)

gre*_*eke 7

使用反斜杠来保护$"在远程命令中:

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