bash - 将交互式命令绑定到键序列
问题描述
在编译和执行涉及 scanf() 的 C 程序时,我遇到了一个有趣的问题。我正在使用带有 Bash 和 GCC v10.2.0 的 Ubuntu 20.04 LTS。
#include <stdio.h>
int main(void)
{
int decimalInteger;
printf("Enter a decimal integer value: ");
scanf("%d", &decimalInteger);
printf("It can also be written in octal and hexadecimal notations as %o and %x, respectively.\nWith C prefixes, they are %#o (for octal) and %#x/%#X (for hexadecimal).\n", decimalInteger, decimalInteger, decimalInteger, decimalInteger, decimalInteger);
return 0;
}
当我用 编译和运行它时gcc-10 *.c -std=c11 && ./a.out
,它工作得非常好。输入后按回车键,光标移至下一行。
使用完整命令输出:
但是,当我添加bind -x '"\C-h":gcc-10 *.c -std=c11 && ./a.out'
到 .bashrc 然后使用 Ctrl+H 编译和执行程序时,输出如下所示:
控制台不显示输入,光标也不移动到下一行。
为什么会这样?
解决方案
这是正常的,readline
在读取输入时更改终端设置。否则无法进行行编辑。
您需要将原始终端设置保存到变量中,并在运行程序之前恢复它们。
stty_orig=$(stty -g)
my_func() {
local stty_bkup=$(stty -g)
stty "$stty_orig"
# compile and run here
stty "$stty_bkup"
}
bind -x '"\C-h": my_func'
推荐阅读
- sql - 按类别划分的第一个用户
- google-apps-script - AppendListItem 创建缺少字形或缩进不当的列表
- reactjs - 在 React 中使用 HOC 创建受控输入
- c++ - 考虑缓存一致性的高性能应用程序的 POD 数学结构类的 C++ 值传递与引用传递选择
- java - 如何模拟 @Autowire 对象的依赖项?
- linux - 如何找出 docker 镜像中安装了哪个 Linux?
- workbench - ST Bluenrg-ms 示例代码
- amazon-web-services - 如何在本地 nodejs 应用程序中从事件桥查询事件?
- python - 代码优化 - 将值列表转换为列
- c# - 如何对 IList 或 List 进行计数、求和等