如何解决错误“bash: !d': event not found"在 Bash 命令替换中 [英] How to address error "bash: !d': event not found" in Bash command substitution

查看:52
本文介绍了如何解决错误“bash: !d': event not found"在 Bash 命令替换中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析 VNC 服务器启动事件的输出,但在命令替换中使用 sed 进行解析时遇到了问题.具体以如下方式启动远程VNC服务器:

I am attempting to parse the output of a VNC server startup event and have run into a problem in parsing using sed in a command substitution. Specifically, the remote VNC server is started in a manner such as the following:

address1="user1@lxplus.cern.ch"
VNCServerResponse="$(ssh "${address1}" 'vncserver' 2>&1)"

此启动事件中产生的标准错误输出随后将被解析以提取服务器和显示信息.此时变量VNCServerResponse的内容如下:

The standard error output produced in this startup event is then to be parsed in order to extract the server and display information. At this point the content of the variable VNCServerResponse is something such as the following:

New 'lxplus0186.cern.ch:1 (user1)' desktop is lxplus0186.cern.ch:1

Starting applications specified in /afs/cern.ch/user/u/user1/.vnc/xstartup
Log file is /afs/cern.ch/user/u/user1/.vnc/lxplus0186.cern.ch:1.log

可以通过以下方式解析此输出以提取服务器和显示信息:

This output can be parsed in the following way in order to extract the server and display information:

echo "${VNCServerResponse}" | sed '/New.*desktop.*is/!d' 
    | awk -F" desktop is " '{print $2}'

结果如下:

lxplus0186.cern.ch:1

我想要做的是在命令替换中使用这种解析,如下所示:

What I want to do is use this parsing in a command substitution something like the following:

VNCServerAndDisplayNumber="$(echo "${VNCServerResponse}" 
    | sed '/New.*desktop.*is/!d' | awk -F" desktop is " '{print $2}')"

尝试执行此操作时,出现以下错误:

On attempting to do this, I am presented with the following error:

bash: !d': event not found

我不知道如何解决这个问题.在命令替换中使用 sed 的方式似乎存在问题.希望得到指导.

I am not sure how to address this. It appears to be a problem in the way sed is being used in the command substitution. I would appreciate guidance.

推荐答案

问题在于,在双引号内,bash 试图在将 !d 传递给子shell 之前对其进行扩展.您可以通过删除双引号来解决这个问题,但我也建议简化您的脚本:

The problem is that within double quotes, bash is trying to expand !d before passing it to the subshell. You can get around this problem by removing the double quotes but I would also propose a simplification to your script:

VNCServerAndDisplayNumber=$(echo "$VNCServerResponse" | awk '/desktop/ {print $NF}')

这只是打印包含桌面"一词的行上的最后一个字段.

This simply prints the last field on the line containing the word "desktop".

在较新的 bash 上,您可以使用 herestring 而不是管道 echo:

On a newer bash, you can use a herestring rather than piping an echo:

VNCServerAndDisplayNumber=$(awk '/desktop/ {print $NF}' <<<"$VNCServerResponse")

这篇关于如何解决错误“bash: !d': event not found"在 Bash 命令替换中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆