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


版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本版权声明
http://www.liaojl.com/archives/2008/01/shell-stty-echo.html

输入密码时不希望密码显示在屏幕上,可以使用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"

发表评论

归档

友情链接

Creative Commons License
此Blog中的日记遵循Creative Commons(知识共享)授权

联系方式