Unbuffered shell-input
Posted 10-16-2021 at 01:46 AM by Michael Uplawski
Updated 11-13-2021 at 12:43 AM by Michael Uplawski (Wrong title, much misunderstanding and ill-chosen search criteria.)
Updated 11-13-2021 at 12:43 AM by Michael Uplawski (Wrong title, much misunderstanding and ill-chosen search criteria.)
There are solutions on the Web.
Having read some of these, I prefer a Ruby-Oneliner “readNB” which returns the 1 character that the user has had a chance to enter on the keyboard, before readNB returns.
In the script I call another routine “wait_for_user”, which I use in my ruby-scripts to provide non-blocking keyboard-input:
The oneliner:
One exemplary use of this in a shell script (bash):
Having read some of these, I prefer a Ruby-Oneliner “readNB” which returns the 1 character that the user has had a chance to enter on the keyboard, before readNB returns.
---------------------- In the meantime -------------------------
GazL has – in the very first comment on this blog, below – presented a better solution with the shell built-in command read: read accepts some parameters and a call like
does the same as my ruby-statement. Details are found in the online-help to read (read --help)Code:read -r -s -N1 [VARIABLE]
-----------------------------------------------------------------------
In the script I call another routine “wait_for_user”, which I use in my ruby-scripts to provide non-blocking keyboard-input:
Code:
require 'io/wait' require 'io/console' # unblocking read from STDIN def wait_for_user() char = nil STDIN.raw do STDIN.noecho do until (STDIN.ready?) sleep(0.1) end char = (STDIN.read_nonblock(1).ord rescue nil) end end return char end
Code:
puts wait_for_user.chr
Code:
#!/bin/bash vim -R -M -p ~/.procmail/log echo -e "\n\tempty log (N/y)?" resp=`readNB` if [ "$resp" == 'y' -o "$resp" == 'Y' ] then echo -e "\tdeleting log..." cat /dev/null > ~/.procmail/log else echo -e "\tokay, doing nothing." fi
Total Comments 4
Comments
-
I may be misunderstanding your requirements, do you really mean non-blocking, or do you mean non-line-buffered?
If the latter, will read -r -s -N1 not serve your needs?Posted 10-18-2021 at 04:19 AM by GazL -
Quote:
Quote:If the latter, will read -r -s -N1 not serve your needs?
Thanks again,
MichaelPosted 10-18-2021 at 03:15 PM by Michael Uplawski -
The non-blocking/unbuffered confusion is due to my reading English texts which only vaguely evoked the documentation that I had in German.
Posted 10-19-2021 at 12:46 AM by Michael Uplawski -
No worries on the language, I just wanted to confirm what it was you were actually looking for.
Within the context of the tty/terminal driver you commonly see it referred to a 'raw' vs 'cooked' input rather than the more verbose "non-line-buffered" I used.Posted 10-19-2021 at 05:27 AM by GazL