>> hello everybody,
>> I am doing a simple shell script exercise in which i expect the user to
>> enter a
>> string ,but instead of the actual characters i want some other character
> to
>> be echoed.
>> i.e If the user enters ABCD, '****' should be echoed in place of ABCD and
>> this should happen before the user presses the enter key.
>> I know, it looks like a password reading application but this is only a
>> learning
>> exercise.
>> with regards
> Sachin,
> It is not the sort of exercise that can be performed, at least easily, in a
> shell script.
Sure it's easy. In bash (2.x) it's builtin:
string=
i=5
while ((i--))
do
read -n 1 -s c || break
s="${s}${c}"
echo -n "*"
done
Of course, You'll want to add in processing for backspace and carriage
return.
In other Bournish shells, you need to use stty and dd:
In SysV Bourne sh:
#!/usr/old/bin/sh
savetty() {
SAVETTY=`stty -g </dev/tty`
}
rawtty() {
stty raw -echo </dev/tty
}
cookedtty() {
stty ${SAVETTY:-cooked} </dev/tty
}
cr=`echo "\r\c"`
bs=`echo "\b\c"`
nl=`echo`
savetty
rawtty
s=
while true
do
c=`dd if=/dev/tty count=1 bs=1 2>/dev/null`
case $c in
$cr) break;;
$nl) break;;
$bs) [ -n "$s" ] && {
echo "\b \b\c"
s=`expr "$s" : '^\(.*\).$'`
}
;;
'') break;;
*) s="${s}${c}";echo "*\c";;
esac
done
cookedtty
echo "\ns=$s"
It's a lot easier in ksh88, easier still in ksh93. But bash
is definitely easiest of all.
--
Dan Mercer
Opinions expressed herein are my own and may not represent those of my employer.