简体   繁体   English

如何在内联 ssh 命令中使用 awk {print}

[英]How to use awk {print} inside an inline ssh command

I am trying to run an inline ssh command which looks like this:我正在尝试运行如下所示的内联 ssh 命令:

ssh user@127.0.0.1 "df / -h | awk 'FNR == 2 {print $3}'"

I would expect the output to be 3.8G (as this is the second line, third column) but instead, I am getting /dev/sda1 6.9G 3.8G 2.8G 58% / (the entire second line).我希望输出为3.8G (因为这是第二行,第三列),但相反,我得到了/dev/sda1 6.9G 3.8G 2.8G 58% / (整个第二行)。

This means that the FNR == 2 is working but the {print $3} is not.这意味着FNR == 2有效,但{print $3}无效。

If I run that command directly on the machine that I am ssh'ing into then I get the expected result, just not when calling it through an inline ssh command as above.如果我直接在我使用 ssh 的机器上运行该命令,那么我会得到预期的结果,只是在通过上面的内联 ssh 命令调用它时不会。

This code will eventually ran within a bash script.此代码最终将在 bash 脚本中运行。 Is it not possible to use print in this way?难道不能用这种方式打印吗? If not, is there another method that you can suggest?如果没有,您是否可以建议另一种方法? I am relatively new to terminal life so please bear with me.我对终端生活比较陌生,所以请耐心等待。

The joys of shell quoting.贝壳报价的乐趣。 The line:线路:

ssh user@127.0.0.1 "df / -h | awk 'FNR == 2 {print $3}'"

Is parsed by the shell, which invokes ssh with two arguments:由 shell 解析,它使用两个参数调用ssh

user@127.0.01 and df / -h | awk 'FNR == 2 {print }' user@127.0.01df / -h | awk 'FNR == 2 {print }' df / -h | awk 'FNR == 2 {print }' The $3 was interpolated, and (I'm assuming) was empty. df / -h | awk 'FNR == 2 {print }' $3是内插的,并且(我假设)是空的。 To prevent that, you have many options.为了防止这种情况,您有很多选择。 One of which is:其中之一是:

ssh user@127.0.0.1 << \EOF
df / -h | awk 'FNR == 2 {print $3}'
EOF

another is:另一个是:

ssh user@127.0.0.1 sh -c '"df / -h | awk '"'"'FNR == 2 {print $3}'"'"'"'

The problem resides in the way you pass you ssh arguments.问题在于您传递ssh参数的方式。

By calling:通过调用:

ssh user@127.0.0.1 "df / -h | awk 'FNR == 2 {print $3}'"

You are passing two arguments:您正在传递两个参数:

  • user@127.0.0.1
  • "df / -h | awk 'FNR == 2 {print $3}'"

Since your second argument is given inside double quotes, the $3 variable will be expanded.由于您的第二个参数在双引号内给出,因此$3变量将被扩展。 You can prevent this variable expansion by escaping the dollar sign:您可以通过转义美元符号来防止这种变量扩展:

ssh user@127.0.0.1 "df / -h | awk 'FNR == 2 {print \$3}'"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM