cwd*_*cwd 10 command-line bash pipe shell-script tail
有时我在一个新的 (ubuntu) 盒子上工作,我输入git并收到警报:
The program 'git' is currently not installed. You can install it by typing:
apt-get install git-core
Run Code Online (Sandbox Code Playgroud)
如果发生这种情况,我知道我可以通过执行以下操作来获取最后一行:
!! 2>&1 | tail -n 1
Run Code Online (Sandbox Code Playgroud)
但是我怎样才能apt-get install git-core最容易地执行那个 ( )的结果呢?
我意识到我可以做到
`!! 2>&1 | tail -n 1`
Run Code Online (Sandbox Code Playgroud)
但是还有一种方法可以实际管道输出并运行它吗?这似乎不起作用:
!! 2>&1 | tail -n 1 | sh
Run Code Online (Sandbox Code Playgroud)
这2>&1部分也有点麻烦,所以我很好奇是否有更简单的方法来实现这一点。
编辑
以某种方式将其保存到变量中,然后执行该变量也是可以接受的:
!! 2>&1 | tail -n 1 | (store as $mycmd)
$mycmd
Run Code Online (Sandbox Code Playgroud)
但我不确定我是否知道通过管道stdout输入变量的方法,至少不知道变量位于命令的右侧。
当您键入系统中不存在的命令时,bash 运行 function command_not_found_handle()。在这个函数中有一个对/usr/lib/command-not-found打印消息的脚本的调用。
我的第一个猜对这个剧本的更改源消息打印到stdout代替stderr,但剧本我时,我正在读源发现,你可以配置,如果你想安装缺失的软件包它只是问你。
如果导出变量COMMAND_NOT_FOUND_INSTALL_PROMPT,系统会要求您安装缺少的包:
pbm@ubuntu:~$ git
The program 'git' is currently not installed. You can install it by typing:
sudo apt-get install git
pbm@ubuntu:~$ export COMMAND_NOT_FOUND_INSTALL_PROMPT=""
pbm@ubuntu:~$ git
The program 'git' is currently not installed. You can install it by typing:
sudo apt-get install git
Do you want to install it? (N/y)y
sudo apt-get install git
[sudo] password for pbm:
Run Code Online (Sandbox Code Playgroud)
不幸的是没有,COMMAND_NOT_FOUND_INSTALL_PROMPT所以我可以找到其他几个选项:
1)从 12.04 安装包 - 这应该不是问题 - 它只是 Python 中的几个脚本,所以它应该可以工作(未经测试!)。
2)stderr改为stdout。为此,请编辑文件/usr/lib/python2.7/dist-packages/CommandNotFound/CommandNotFound.py并更改stderr为stdout第 237 和 240 行。
之后,您可以通过以下方式使用它:
pbm@ubuntu:~$ git
The program 'git' is currently not installed. You can install it by typing:
sudo apt-get install git
pbm@ubuntu:~$ `git`
//Installation begins
Run Code Online (Sandbox Code Playgroud)
如果您在第 237 和 240 行中-y为apt-get命令添加选项,您还可以使用 syntax !! | sh。
3) 您还可以通过这种方式从第 242 行修改此脚本:
print >> sys.stderr, _("You can install it by typing:")
f = open("%s/.install-missing" % os.path.expanduser('~'),'w')
print >> sys.stderr, "sudo apt-get install %s" % packages[0][0]
print >> f, "sudo apt-get install %s" % packages[0][0]
f.close()
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您将在 file 中获取您的命令~/.install-missing,因此您可以创建别名:
alias im="chmod +x ~/.install-missing; ~/.install-missing"
Run Code Online (Sandbox Code Playgroud)
如果你调用im包将被安装。