将输入中的文本更改为星号

将输入中的文本更改为星号

我已经问过这个问题了,现在我有另一个问题。这是我的代码:

#! /bin/bash
read -p 'Username:' name
read -p 'Password:' pass
echo
echo Confirm Username: $name?
echo "Confirm Password: ${pass//?/*}"
echo Let us start the quiz :P 
echo
echo Q1 - Full form of MCQ
echo a - Maximum Capture Quest
echo b - Multiple Choice Question
read -p "Your Answer:" word

if [[ $word == "b" ]]
then
  echo "Correct! V.Good"
else
  echo "Wrong. U Suck"
fi

我希望这部分 ( read -p 'Password:' pass) 的输入用星号表示。

答案1

回显作为星号输入的字符?乔恩·雷德(Jon Red)获得了第一名,但这是另一个:

#!/bin/bash                     

# read a string, prompting using "$1"
# echo characters entered as asterisks
# value is returned in variable `pass`  
readpw() {              
        printf "%s" "${1-}"
        pass=
        local char
        while IFS= read -r -s -n1 char; do
                if [[ $char = "" ]] ; then
                        # enter, end
                        printf "\n"
                        break
                elif [[ $char = $'\177' ]] ; then
                        # backspace, remove one char
                        if [[ $pass != "" ]] ; then
                                pass=${pass%?}
                                printf '\b \b'
                        fi
                else
                        # any other char
                        pass+=$char                 
                        printf "*"
                fi
        done
}

readpw "Enter Password: "
printf "Password entered was: %s\n" "$pass"

答案2

也许是这样的?

#! /bin/bash

read -p 'Username:' name

# read -p 'Password:' pass
unset pass
prompt="Enter Password:"
while IFS= read -p "$prompt" -r -s -n 1 char
do
    if [[ $char == $'\0' ]]
    then
        break
    fi
    prompt='*'
    pass+="$char"
done

echo
echo Confirm Username: $name?
echo "Confirm Password: ${pass//?/*}"
echo Let us start the quiz :P
echo
echo Q1 - Full form of MCQ
echo a - Maximum Capture Quest
echo b - Multiple Choice Question
read -p "Your Answer:" word
if [[ $word == "b" ]]
then
  echo "Correct! V.Good"
else
  echo "Wrong. U Suck"
fi

相关内容