直到用户输入匹配变量 do [英] Until user input matches variable do
问题描述
好的,所以我正在尝试创建一个用户名/密码登录脚本.(可能不是我仍在研究的最安全的想法);)
Okay, so I'm trying to create a username/password login script of sorts. (may not be the most secure idea I'm still working on it) ;)
我的脚本将加载变量以与来自这样的文件进行比较.(现在我只是在处理密码部分)
My script will load variables to compare to from file like this. (right now I'm just working on password portion)
./path/to/variables.conf
此文件将包含一个名为
This file will contain a variable called
PASS=SOME_VALUE
我打算用read来获取要比较的变量
I plan to use read to obtain the variable that will be compared
read -p "Enter your password:" CPASS;
现在我缺少的部分(我设想它是如何工作的)
Now the part I'm missing (how I envision it working)
while "$CPASS" doesn't match "$PASS" do
read -p "Wrong password, try again:" CPASS;
谢谢你&任何帮助表示赞赏.
Thank you & any help is appreciated.
推荐答案
这个应该可以.您只需要 [ ]
大括号和 !=
运算符即可 比较 bash 中的字符串:
This should do it. You just need [ ]
braces and the !=
operator to compare strings in bash:
PASS=SOME_VALUE
read -p "Enter your password:" CPASS
while [ "$CPASS" != "$PASS" ]; do
read -p "Wrong password, try again:" CPASS
done
还请注意,强烈建议将 -s
参数传递给读取,这样输入的密码就不会回显给用户.从 man bash
的 read
部分:
Also note it would be highly advisable to pass the -s
parameter to read, so that the entered password is not echoed back to the user. From the read
section of man bash
:
-s Silent mode. If input is coming from a terminal, char-
acters are not echoed.
请注意,当用户按 ENTER 时,也不会有换行符回显给用户,因此您必须在每次 read
之后手动插入换行符,以便正确格式化行.因此,您可能应该将您的 read 语句替换为以下内容:
Note though that there will also be no newline echoed back to the user when the user hits ENTER, so you'll have to manually insert a newline after every read
so that lines are properly formatted. So you should probably replace your read statements with something like this:
read -s -p "Enter your password:" CPASS
echo
这篇关于直到用户输入匹配变量 do的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!