How do I read characters from the terminal in a shell script?

How do I read characters from the terminal in a shell script?

In sh, use read. It is most common to use a loop like

while read line
do
...
done

In csh, use $< like this:

while ( 1 )
set line = "$<"
if ( "$line" == "" ) break
...
end

Unfortunately csh has no way of distinguishing between a blank
line and an end-of-file.

If you're using sh and want to read a *single* character from the
terminal, you can try something like

echo -n "Enter a character: "
stty cbreak # or stty raw
readchar=`dd if=/dev/tty bs=1 count=1 2>/dev/null`
stty -cbreak

echo "Thank you for typing a $readchar ."



Home FAQ