Read a single character in shell

Sometime as IT we need to develop shell script who interact with end users (yeuk). In these programs you may want to ask the user question like press any key to continue. Also for ease of use you may want to ask them to press the key Y or N to confirm or not an action, without asking them to press return each time you ask a question. Here an example on how to do that in your favorite shell.

anykey() {
    stty cbreak -echo
    KEY=`dd bs=1 count=1 2>/dev/null`
    stty -cbreak echo
    echo $KEY
}

anykey() {
stty cbreak -echo
KEY=`dd bs=1 count=1 2>/dev/null`
stty -cbreak echo
echo $KEY
}

Usage:

echo -n "Press any key: " && anykey

echo -n "Press any key: " && anykey
 

Leave a message

(Required)
(Required and not displayed)
(Optional)
obfuscated letters Enter the text shown in the image