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"

Leave a comment

Archives

Creative Commons License
This blog is licensed under a Creative Commons License.