【问题标题】:How do I turn off echo in a terminal?如何关闭终端中的回声?
【发布时间】:2011-08-03 18:11:55
【问题描述】:

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

echo -n 'Password: '
read password

显然,我不希望将密码回显到终端,因此我想在读取期间关闭回显。我知道stty 可以做到这一点,但我会在阅读手册页时为社区的利益提出这个问题。 ;)

【问题讨论】:

标签: unix terminal sh


【解决方案1】:
stty_orig=`stty -g`
stty -echo
echo 'hidden section'
stty $stty_orig

【讨论】:

  • 如果没记错的话,这肯定是我以前做过的方式。只是出于好奇,这和stty -echo; read foo; stty echo 有什么不同吗?
  • 是的,它会在之后关闭回声,以防它已经关闭。
  • 我是 unix 新手。你能解释一下 stty 到底是什么以及这段代码在做什么吗
  • 更笼统,当你是 unix 新手时比维基百科更好@AbhishekGupta:1. 学习如何滚动、搜索和退出less(或more)。 2. man whateveryouwonderabout 或者,对于诸如“set”之类的 bash 内置命令,help set。祝你旅途愉快;-)
【解决方案2】:

read -s password 在我的 linux 机器上工作。

【讨论】:

  • 这是有用的信息,但 -s 似乎是 Bash 扩展,因为 read -s foo 在 Dash 中生成 read: 1: Illegal option -s(Ubuntu 符号链接到 /bin/sh 的 Bourne shell)。
【解决方案3】:

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

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

如果您想从终端隐藏打印,您也可以使用 'stty -echo'。并使用 "stty echo"

恢复终端设置

但我认为从用户 'read -s password' 获取密码输入已经绰绰有余了。

【讨论】:

  • 是 stty,不是 ssty。
【解决方案4】:

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 手动 sn-ps:

 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

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2020-09-19
    • 2016-09-01
    • 2018-08-19
    相关资源
    最近更新 更多