如何关闭终端中的回声?

时间:2011-04-12 10:01:33

标签: unix terminal sh

我正在编写一个Bourne shell脚本,并输入如下密码:

echo -n 'Password: '
read password

显然,我不希望密码被回显到终端,所以我想在读取期间关闭回声。我知道有stty的方法可以做到这一点,但是当我阅读联机帮助页时,我会问社区的好处。 ;)

4 个答案:

答案 0 :(得分:38)

stty_orig=`stty -g`
stty -echo
echo 'hidden section'
stty $stty_orig

答案 1 :(得分:13)

read -s password适用于我的linux盒子。

答案 2 :(得分:2)

您可以使用' - s'选项读取命令来隐藏用户输入。

echo -n "Password:"
read -s password
if [ $password != "..." ]
then
        exit 1; # exit as password mismatched #
fi

如果您想隐藏终端以进行打印,也可以使用 'stty -echo' 。并使用 “stty echo”

恢复终端设置

但我认为从用户 '读取密码' 获取密码已经足够了。

答案 3 :(得分:0)

Bourne Shell脚本:

#!/bin/sh

# Prompt user for Password
echo -n 'Password: '

# Do not show what is being typed in console by user
stty -echo

# Get input from user and assign input to variable password
read password

# Show what is being typed in console
stty echo

stty手动命令获取更多信息:

@:/dir #man stty

stty手动摘录

 STTY(1)              stty 5.2.1 (March 2004)              STTY(1)

     NAME
          stty - change and print terminal line settings

     SYNOPSIS
          stty [-F DEVICE] [--file=DEVICE] [SETTING]...
          stty [-F DEVICE] [--file=DEVICE] [-a|--all]
          stty [-F DEVICE] [--file=DEVICE] [-g|--save]

     DESCRIPTION
          Print or change terminal characteristics.

          -a, --all
               print all current settings in human-readable form

          -g, --save
               print all current settings in a stty-readable form

          -F, --file=DEVICE
               open and use the specified DEVICE instead of stdin

          --help
               display this help and exit

          --version
               output version information and exit

          Optional - before SETTING indicates negation.  An * marks
          non-POSIX settings.  The underlying system defines which
          settings are available.



   Local settings:

          [-]echo
               echo input characters