I'm facing an interesting problem while compiling and executing a C program involving scanf(). I'm using Ubuntu 20.04 LTS with Bash and 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;
}
When I compile and run this with gcc-10 *.c -std=c11 && ./a.out
, it works perfectly fine. Upon pressing the enter key after the input, the cursor moves to the next line.
Output using full command:
But, when I add bind -x '"\C-h":gcc-10 *.c -std=c11 && ./a.out'
to .bashrc and then use Ctrl+H to compile & execute the program, the output looks like this:
The console doesn't display the input, and the cursor doesn't move to the next line.
Why is this happening?
This is normal, readline
changes terminal settings while reading input. Line editing wouldn't be possible otherwise.
You need to save original terminal settings into a variable, and restore them before running your program.
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'