read without Enter

A small unix tip today.

Do you want to continue ?

If you are expecting “y” or “n” but do not want to enforce the user to type y[Enter] but simply y, you can use the -n option in bash.

Within a ksh script:

yorn=$(bash -c 'read -p "Do you want to continue ? " -n 1 ans;echo "$ans"')

Within bash:

read -n 1 yorn

2 Comments

  • You can do it in ksh without having bash installed.
    Just change the tty settings to raw with no echo and use dd to read 1 character.

    key=$(os=$(stty -g);stty raw -echo;dd if=/dev/tty bs=1 count=1 2>/dev/null;stty $os)

    Just web search for ksh stty dd

    GP>

Leave a Reply

Your email address will not be published.