Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux bash - reprint user's input

Tags:

linux

bash

I have an old shell script which needs to be moved to bash. This script prints progress of some activity and waits for user's commands. If no action is taken by user for 15 seconds screen is redrawn with new progress and timer starts again. Here's my problem:

I am trying to use read -t 15 myVar - this way after 15 seconds of waiting loop will be restarted. There is however a scenario which brings me a problem:

  • screen redrawn and script waits for input (prints 'Enter command:')
  • user enters foo but doesn't press enter
  • after 15 seconds screen is again redrawn and script waits for input - note, that foo is not displayed anywhere on the screen (prints 'Enter command:')
  • user enters bar and presses enter

At this moment variable $myVar holds 'foobar'.

What do I need? I am looking for a way to find the first string typed by user, so I could redisplay it after refreshing status. This way user will see: Enter command: foo

On Solaris I could use stty -pendin to save input into some sort of a buffer, and after refresh run stty pendin to get this input from buffer and print it on a screen.

Is there a Linux equivalent to stty pendin feature? Or maybe you know some bash solution to my problem?

like image 394
Patryk Baranowski Avatar asked Jul 12 '26 23:07

Patryk Baranowski


1 Answers

I guess one way would be to manually accumulate the user input ... use read with -n1 so that it returns after every character, then you can add it to your string. To prevent excessive drawing you would have to calculate how many remaining seconds are on the 15 second clock ...


Addendum:

For your comment about space/return - you basically want to use an IFS without the characters you want, such as space

example:

XIFS="${IFS}"  # backup IFS
IFS=$'\r'      # use a character your user is not likely to enter (or just the same but w/o the space)


# Enter will look like en empty string
$ read -n1 X; echo --; echo -n "${X}" | od -tx1

--
0000000


# space will be presented as a character
$ read -n1 X; echo --; echo -n "${X}" | od -tx1
 --
0000000 20
0000001


# after you are all done, you probably wantto restore the IFS
IFS="${XIFS}"
like image 100
nhed Avatar answered Jul 15 '26 12:07

nhed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!