Patch
Patch

Reputation: 754

Bash read message every X seconds

I want the read command to be able to use read -t without deleting the message after the timeout. basically, I need to read the data. After t seconds stop reading the data and save it in some variable.

For example: read -t 5 msg but after 5 seconds the message will still be at msg or any other variable

Upvotes: 0

Views: 403

Answers (1)

that other guy
that other guy

Reputation: 123700

Normally the terminal is line buffered, so bash never sees anything the user types until they press Enter.

To get around this, you will need to read character by character:

echo "Enter some data in 5 seconds:"
str=""
SECONDS=0
while ((SECONDS < 5))
do
  # Read one character with a very short timeout,
  # so that we can go back to checking the global timer
  IFS="" read -r -n 1 -d "" -t 0.1 c
  str+="$c"
done
echo
echo "Time's up. You wrote: $str"

Note that since line buffering is no longer used, you will need to include your own backspace handling.

Upvotes: 3

Related Questions