将交互式命令绑定到键序列

Bind interactive command to a key sequence

我在编译和执行涉及 scanf() 的 C 程序时遇到了一个有趣的问题。我正在使用 Ubuntu 20.04 LTS 与 Bash 和 GCC v10.2.0.

#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'