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

Published by

Laurent Schneider

Oracle Certified Master

2 thoughts on “read without Enter”

  1. 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.


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>