按下快捷键时如何在shell中执行脚本

use*_*539 19 bash keyboard-shortcuts gnome-terminal

当按下快捷键时,如何在 Shell 中执行脚本。

基本上我需要的是当按下快捷键时脚本应该从文件中读取并在终端中显示该内容。

slm*_*slm 27

您可以使用内置命令bind来映射键盘快捷键,以便它执行命令/shell 脚本。

例子

假设我们要pwd在按下F12键时运行命令。

$ bind '"\e[24~":"pwd\n"'
Run Code Online (Sandbox Code Playgroud)

现在,当我按F12提示时,$

$ pwd
/home/saml
Run Code Online (Sandbox Code Playgroud)

确定键盘快捷键

您可以使用以下技术来确定给定键盘快捷键的转义码。在大多数系统上,按Ctrl+ V,松开,然后按您想要代码的键。还有一些其他系统可以使用,M而不是V

例子

Ctrl+V然后释放两个CtrlV最后F12在终端窗口中按下 返回:

$ ^[[24~
Run Code Online (Sandbox Code Playgroud)

这个输出可以解释如下,^[Esc关键。因此,当我们想使用bind命令指定这个特定的键时,我们需要使用 a\e来表示Esc键,然后是上面的其他所有内容。所以bind命令看起来像这样:

$ bind '"\e[24~":"....."'
Run Code Online (Sandbox Code Playgroud)

中途执行命令

您还可以使用bind -x设置键盘快捷键,当您在提示符下键入内容时将运行命令,并且将显示这些命令的输出,但您在提示符下键入的内容将保持不变。

$ bind -x '"\eW":"..."'
Run Code Online (Sandbox Code Playgroud)

注意:此方法仅适用于输出 1 个字符的键盘快捷键,因此F12在此处不起作用。

例子

让我们为键盘快捷键Alt+ Shift+取别名W

$ bind -x '"\eW":"who"'
Run Code Online (Sandbox Code Playgroud)

假设我正在输入命令finger

$ finger
Run Code Online (Sandbox Code Playgroud)

现在我按下键盘快捷键Alt+ Shift+ W

saml     tty1         2013-09-01 11:01 (:0)
saml     pts/0        2013-09-01 11:03 (:0.0)
saml     pts/1        2013-09-01 11:05 (:0.0)
saml     pts/2        2013-09-01 11:05 (:0.0)
saml     pts/5        2013-09-03 22:45 (:0.0)
$ finger
Run Code Online (Sandbox Code Playgroud)

发生的事情bind是运行定义的命令, who,获取其输出并将其插入到提示前。如果你重复它,你会看到发生了什么,这是我击中它 2 次的输出:

saml     tty1         2013-09-01 11:01 (:0)
saml     pts/0        2013-09-01 11:03 (:0.0)
saml     pts/1        2013-09-01 11:05 (:0.0)
saml     pts/2        2013-09-01 11:05 (:0.0)
saml     pts/5        2013-09-03 22:45 (:0.0)
saml     tty1         2013-09-01 11:01 (:0)
saml     pts/0        2013-09-01 11:03 (:0.0)
saml     pts/1        2013-09-01 11:05 (:0.0)
saml     pts/2        2013-09-01 11:05 (:0.0)
saml     pts/5        2013-09-03 22:45 (:0.0)
$ finger
Run Code Online (Sandbox Code Playgroud)

你的问题

所以一个想法是使用bind -x上面的方法并cat在你的提示下显示这个文本文件:

$ bind -x '"\eW":"cat someinfo.txt"'
Run Code Online (Sandbox Code Playgroud)

现在,当我运行命令时,我可以像这样看到这个文件:

This is text from some 
multi-line file reminding
me how to do some 
stuff
$ finger 
Run Code Online (Sandbox Code Playgroud)

文件的输出someinfo.txt显示在我finger上面的命令上方。

参考