Monday, February 16, 2009

Press Any Key To Continue

If you need to prompt the user to "Press any key to continue", the user would just expect to hit a single key to continue instead of any key + a carriage return. If you use:
echo -e "Press any key to continue. \c"; read any,
the user will need to hit the "Return key" to complete the sequence. With stty, you can achieve this without the user hitting an additional carriage return key. The below function anykey will do this trick.

The steps in the function:

  1. save original terminal setting
  2. print the message (without a carriage return)
  3. turn off the echo input character to hide your key press
  4. set terminal into a raw mode
  5. use dd to a single character from terminal
  6. revert back the original terminal setting

anykey ()
{
    orig=`stty -g`;
    echo -e "Press any key to continue. \c";
    stty -echo;
    stty raw;
    any=`dd if=/dev/tty bs=1 count=1 2>/dev/null`;
    stty $orig
}

Labels:

0 Comments:

Post a Comment

<< Home