-1

As per triplee, samuel suggestion, I edited my question here, replaced the previous one that was confusing, hoping this new round will be more understable.

The question could be how to drain any type ahead on the stdin before issuing a Query/Reply sequence to a terminal emulator.

The demo below emulate a command loop in a script, read a user 'command', do this action (here a sleep) then 'would like' to query/reply the terminal emulator (here asking for term ID, but you can imagine any kind of query a terminal emulator would accept) so before the query/reply we must drain any type ahead. Here I attempted a read until empty.

Here is the script

 typeset -i i=0 n=30
while((i<n))
do
  read -p "cmd: "  c          # Read user command
  sleep 1                     # emulate user command that takes time
  echo "cmd '$c' done"
  while read -s -n 1 -t .1 a  # drain type ahead
  do [ "$a" = "" ] && break;
  done
  read -s -dc -p $'\e[0c' r  # emit a terminal query and read reply.
  [ "$r" != "$gr" ] && echo "Got corrupted reply '$r' '$gr'"
  ((i++))
done

When run it type a 1 letter command 'a' then do this slowly, once every sec.

Using bash BASH_VERSION='4.4.19(1)-release' with both mate-terminal, or xterm I got this

Typing a once per second

cmd: a
cmdcmd 'a' done
cmdcmd: a
cmdcmd 'a' done
cmdcmd: a
cmdcmd 'a' done
cmdcmd: 

Typing 'a' as fast as I can I get.

 cmdcmd: a
cmda
cmda
cmda
cmda
cmdacmd 'a' done
cmdGot corrupted reply 'a
cmda
cmda
cmda
cmdmd: 
cmda
cmda
cmda
cmda
cmdcmd '' done
cmdGot corrupted reply 'a
cmda

So the question, what is the way to drain the input to remove unwanted type ahead.

Phi
  • 735
  • 7
  • 22

1 Answers1

0

read -d ':' _ will read input until the first colon.

while read -d :
do
  printf 'Preread: Got "%s"\n' "$REPLY"
  read -r a
  printf 'In loop: Got "%s"\n' "$a"
done <<\_
bad
bad
: good
bad
bad
: good
bad
bad
: good
bad
bad
: good
_

Output:

Preread: Got "bad
bad
"
In loop: Got "good"
Preread: Got "bad
bad
"
In loop: Got "good"
Preread: Got "bad
bad
"
In loop: Got "good"
Preread: Got "bad
bad
"
In loop: Got "good"
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanx for the -d, it simplify the test case, but still no joy, still got the bad input. – Phi Jan 20 '19 at 13:36