Bind a key to a command that reads stdin

I have a script that reads a string from stdin and performs some operations based on the contents of the string. I need to bind a key to this script so that it can be simply typed by typing Ctrl-t. When I call a script by its name, it works as expected, but when I click on the key binding, it hangs. In fact, the shell is hanging, and I have to kill it. The script uses read -r line . I tried with cat with the same results.

The script looks like this (read.sh file name):

 #!/bin/bash echo -n ' > ' read -r buf echo "you typed $buf" 

Bind as:

 bind -x '"\Ct" : "read.sh"' 
+5
source share
1 answer

Your terminal settings are different if you press Ctrl + t , unlike when you run a script through the terminal. If you add the following line to read.sh , it will print your terminal settings:

 echo Terminal settings: "$(stty -a)" 

Now run the script yourself, and then run it by pressing Ctrl + t . You will notice several differences, the biggest of which are the additions -echo and -icrnl , which disable echo and change newline processing. This results in a hanging script.

You can fix this problem inside the script by making tty return to canonical mode and re-add the echo. Before making any changes to stty, you will want to save the settings and restore them when the script exits. You can use trap for this.

 #!/bin/bash # Save the tty settings and restore them on exit. SAVED_TERM_SETTINGS="$(stty -g)" trap "stty \"${SAVED_TERM_SETTINGS}\"" EXIT # Force the tty (back) into canonical line-reading mode. stty cooked echo # Read lines and do stuff. echo -n ' > ' read -r buf echo "you typed $buf" 
+2
source

Source: https://habr.com/ru/post/1247832/


All Articles