Shell 输入密码时关闭屏幕回显

(0 comments)

输入密码时不希望密码显示在屏幕上,可以使用stty -echo关闭回显。

#!/bin/sh
stty -echo
echo -n "Please set your password: "
read p
stty echo
echo -e "\nYour password is: $p"

关闭回显后,读入用户的回车符号不会导致屏幕换行,因此后面加上"\n"来换行。

还有一种方法是将输入密码字符显示为'*',下面脚本有一个已知的缺陷,不能支持退格键。

#!/bin/sh
 
getchar() {
    stty cbreak -echo
    dd if=/dev/tty bs=1 count=1 2> /dev/null
    stty -cbreak echo
}
 
printf "Please input your passwd: "
 
while : ; do
    ret=`getchar`
    if [ x"$ret" = x ]; then
        echo
        break
    fi
    str="$str$ret"
    printf "*"
done
 
echo "Your password is: $str"
Currently unrated

Comments

There are currently no comments

New Comment

required

required (not published)

optional

required