运行 bash 命令通过 ssh 时出错

Error when running bash command over ssh

尝试通过 ssh 运行 以下命令时:

ssh hostname 'for pid in $(ps -ef | grep "some process" | awk '{print }'); do kill -9 $pid; done'

我收到以下错误:

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

我试过用不同的方式逃脱,但没有找到正确的方式 - 或者可能是其他原因?

提前致谢!

您不能将单引号包含在单引号字符串中,因为除了关闭字符串的单引号外,不会在其中解释任何内容。您可以使用 "'":

连接单引号字符串
ssh host 'for pid in $(ps -ef | grep "some process" | awk '"'"'{print }'"'"'); do kill -9 $pid; done'

或者,连接转义的单引号 (\'):

ssh host 'for pid in $(ps -ef | grep "some process" | awk '\''{print }'\''); do kill -9 $pid; done'

参见Strong Quoting

错误原因

您的命令被解释为一对 $IFS 分隔的参数:

  • for pid in $(ps -ef | grep "some process" | awk {print
  • }); do kill -9 $pid; done

字符串中没有</code>,因为<code>被解释为一个shell变量,而这个变量在正常shell上下文中的值是空.

因此,您向服务器发送了以下命令:

for pid in $(ps -ef | grep "some process" | awk {print }); do kill -9 $pid; done

如果你在终端中 运行 这个命令,你会从 AWK 得到同样的错误。