如何在单个ssh命令中使用bash $(awk)? [英] How to use bash $(awk) in single ssh-command?
问题描述
我正在尝试在ssh
上执行一个包含`sub-code`或$(sub-code)的命令(我一直使用它,但我不知道它的正式名称)首先执行,但在目标服务器上执行.
I am trying to execute a single command over ssh
that contains `sub-code` or $(sub-code) (I use it all the time but I don't know the official name for that) to be executed first, but on the target server.
为了论证,让我们说这是我要使用的命令.当然,可以使用hostname
完成此操作,但这只是一个简化的示例,其中包含我要使用的所有格式设置向导.
For the sake of argument, let's say this is the command I want to use. Ofcourse this can be done with hostname
, but this is just a simplified example that contains all the formatting wizardry I want to use.
echo `uname -a | awk '{print $2}'`
没问题.但是,如何在单个命令中正确转义以通过ssh
发送它呢?以下是错误的,因为它允许服务器回复您的本地主机名.子代码在本地执行:
No problem. But how do you escape this properly to send it over ssh
in a single command? The following is wrong, because it lets the server reply your local hostname. The sub-code is executed locally:
ssh myServer echo `uname -a | awk '{print $2}'`
但是想到的任何逃避现实都行不通:
But any escape-ishness that comes to mind doesn't work:
$ ssh myServer echo \`uname -a | awk '{print $2}'\`
awk: cmd. line:1: {print $2}`
awk: cmd. line:1: ^ invalid char '`' in expression
$ ssh myServer echo \$(uname -a | awk '{print $2}')
bash: syntax error near unexpected token `('
$ ssh myServer echo \$\(uname -a | awk '{print $2}')
bash: syntax error near unexpected token `)'
$ ssh myServer echo \$\(uname -a | awk '{print $2}'\)
awk: cmd. line:1: {print $2})
awk: cmd. line:1: ^ syntax error
bash: -c: line 0: unexpected EOF while looking for matching `)'
bash: -c: line 1: syntax error: unexpected end of file
我想要一个答案,其中包括使用正确转义的` or $() because I'd like to know if it's possible.
echo`可能会更复杂.
I would like an answer that includes using properly escaped ` or $() because I'd like to know if it's possible.
echo` could be something more complicated.
推荐答案
尝试一下
ssh myServer "uname -a | awk '{print \$2}' "
使用双引号"
可以对将要远程执行的命令进行分组.
Use the double quotes "
in order to group the commands you will execute remotely.
您还需要在$2
参数中对$
进行转义,以便它不是在本地计算的,而是远程传递给awk
的.
You also need to escape the $
in the $2
argument, so that it is not calculated locally, but passed on to awk
remotely.
如果要包含$(
)
,则必须再次转义$
符号,如下所示:
If you want to include the $(
)
, you again have to escape the $
symbol, like this:
ssh myServer "echo \$(uname -a | awk '{print \$2}') "
您还可以像这样逃避反引号`:
You can also escape the backtick `, like this:
ssh myServer "echo \`uname -a | awk '{print \$2}'\` "
这篇关于如何在单个ssh命令中使用bash $(awk)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!