45.32 A Better read Command: grabchars
By default, grabchars will obtain one character from the standard input, echo that character to the standard output, and return an exit status ( 44.7 ) of one - meaning one character was read. Options (see the manual page) accept more than one character, accept only certain characters, prompt the user, and more. Here's an example. With the standard echo ( 8.6 ) and read ( 44.13 ) commands, you'd prompt a user this way:
echo -n "Answer y or n, then press RETURN: " read ans With grabchars , a prompt can be printed to standard error, the user's answer read as soon as the character is pressed, and backquotes ( 9.16 ) used to grab the standard output (the user's answer, echoed by grabchars ):
ans=`grabchars -q'Answer y or n: '` By default, the answer that grabchars reads and echoes will be "eaten" by the backquotes; the user won't see what she typed. That's nice when the answer needs to be a secret. To show the answer, you have two choices:
The option
ans=`grabchars -c'yn' -q'Answer y or n: '` There are lots of other options. I'd like to explain two more. (Please look at the manual page for the rest.) You can give grabchars a time limit with the -t option. If the user doesn't answer by then, grabchars can quit - and also give a default answer from the -d option. The timeout option lets you write shell scripts where you can offer some assistance if it's obvious that the user might be stuck - or to let a user answer a prompt only if he doesn't want the default. For example:
ans=`grabchars -t5 -d'y' -q'To stop, type n within 5 seconds: '` If the user doesn't type anything in 5 seconds, grabchars will answer y automatically. - , |
|