Ash*_*ey 1 validation bash shell
我有一个脚本要求用户输入用户名和密码.我想将输入与存储在passwords.txt文件中的用户名和密码变量进行比较.我尝试使用source,但它不允许我访问变量.以下是我的文件部分:
password.txt的
#!/bin/bash
username="username"
password="password"
Run Code Online (Sandbox Code Playgroud)
script.bash
#!/bin/bash
echo "Enter username"
read -r user
echo "Enter password"
read -r pass
source passwords.txt
if("$user" == "$username" && "$pass" == "$password") then
echo "You have successfully logged in"
else
echo "You entered the wrong credentials"
fi
Run Code Online (Sandbox Code Playgroud)
如果可以的话,请帮我弄清楚如何比较不同文件中的两个变量.
问题不在于采购,而在于您的if声明的语法.
也就是说,将明文密码存储在文件中并提示用户输入明显的密码是出于安全原因要避免的做法.
除此之外,这里是Bash代码,它显示了条件的正确形式:
echo "Enter username"
read -r user
echo "Enter password"
read -r pass
source passwords.txt
if [[ "$user" == "$username" && "$pass" == "$password" ]]; then
echo "You have successfully logged in"
else
echo "You entered the wrong credentials"
fi
Run Code Online (Sandbox Code Playgroud)
通常,请考虑使用shellcheck.net在shell代码中查找语法问题.
在您的具体情况中,正如您在评论中指出的那样,shellcheck.net不会有帮助,但是:
(...)作为条件传递到if 是在原理上有效的,用于执行命令,其退出代码以测试(虽然封闭在(...)通常不需要的是,因为所有确实是在运行的命令子shell).
相比之下,你正在寻找评估的表达,这是什么语法[[ ... ]]是-看猛砸手册在线或部分CONDITIONAL EXPRESSIONS在man bash.