【问题标题】:Bind interactive command to a key sequence将交互式命令绑定到键序列
【发布时间】:2020-12-27 12:54:03
【问题描述】:

在编译和执行涉及 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 &amp;&amp; ./a.out 编译和运行它时,它工作得非常好。输入完成后按回车键,光标移动到下一行。

使用完整命令输出:

但是,当我将bind -x '"\C-h":gcc-10 *.c -std=c11 &amp;&amp; ./a.out' 添加到 .bashrc 中,然后使用 Ctrl+H 编译并执行程序时,输出如下所示:

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

为什么会这样?

【问题讨论】:

    标签: bash readline


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-14
      • 2012-09-28
      • 2010-12-05
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多