Download sttydemo.sh
#!/bin/sh
# sttydemo.sh - Demonstrate fancy uses of stty
# This script shows how to read in one keystroke (without waiting
# for the newline, and without erase or kill processing. For
# extra fun we create a function that echos "*" and processes
# erase (backspace key), to allow input of passwords from the tty.
#
# Written 4/2007 by Wayne Pollock, Tampa Florida USA.
# $Id: sttydemo.sh,v 1.3 2007/05/01 18:32:30 wpollock Exp $
PATH=/bin:/usr/bin
# Save current temios settings, so can restore later:
savedterm=$(stty -g)
# Function to read next keypress from STDIN into $REPLY:
getKey()
{ stty -icanon
REPLY=$(dd bs=1 count=1 2>/dev/null)
stty $savedterm
}
# Function to read in a line of input from keyboard, echoing stars,
# and processing erase (backspace):
getPassword()
{ BS=$(tput kbs) # BS = the char generated by the backspace key
stty -icanon -echo
REPLY=
while :
do CHAR=$(dd bs=1 count=1 if=/dev/tty 2>/dev/null) # read 1 character
case "$CHAR" in
"$BS") if [ -n "$REPLY" ]; then # Lop off last character
tput kbs; REPLY=${REPLY%?}
fi ;;
"") printf "\n"; break ;; # A newline was read
*) printf '*'
REPLY="$REPLY$CHAR" # Append CHAR to REPLY
;;
esac
done
stty $savedterm
}
REPLY=
while :
do
printf "\n\n Menu:\n A) Add\n D) Delect\n P) Password\n Q) Quit\n"
printf "Enter your choice: "
getKey
REPLY=$(printf "%s\n" "$REPLY" | tr [:lower:] [:upper:])
echo
case "$REPLY" in
A) printf ' ** You did "Add".' ;;
D) printf ' ** You did "Delete".' ;;
P) printf '\n\tEnter password: '
getPassword
printf '\tYour password is "%s".\n' "$REPLY"
;;
Q) echo; break ;;
*) printf '*** Error, unrecognized command!' ;;
esac
done