首页 > 解决方案 > 将交互式命令绑定到键序列

问题描述

在编译和执行涉及 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 编译和执行程序时,输出如下所示:
这个

控制台不显示输入,光标也不移动到下一行。

为什么会这样?

标签: bashreadline

解决方案


这是正常的,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'

推荐阅读