简体   繁体   English

验证另一个bash脚本中的变量

[英]Validate variables from another bash script

I have a script that asks for the user to enter a username and password. 我有一个脚本,要求用户输入用户名和密码。 I want to compare the input to the username and password variables stored in a passwords.txt file. 我想将输入与存储在passwords.txt文件中的用户名和密码变量进行比较。 I tried using source but it does not give me access to the variables. 我尝试使用源代码,但是它不能让我访问变量。 Here are my parts of my files below: 以下是我的部分文件:

passwords.txt passwords.txt

 #!/bin/bash 
 username="username"
 password="password"

script.bash 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 

If you can, please help me figure out how to compare the two variables in different files. 如果可以的话,请帮我弄清楚如何比较不同文件中的两个变量。

The problem is not with sourcing, but with the syntax of your if statement. 问题不在于源,而在于if语句的语法。

That said, storing plain-text passwords in files and prompting users for passwords typed visibly are both practices to be avoided for security reasons. 也就是说,将纯文本密码存储在文件中并提示用户输入可见的密码都是出于安全原因而应避免的做法。

With that out of the way, here's the Bash code that shows the proper form of the conditional: 有了这些,下面的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 

Generally, consider using shellcheck.net to find syntax problems in your shell code. 通常,考虑使用shellcheck.net在您的Shell代码中查找语法问题。

In your specific case, as you point out in a comment, shellcheck.net wouldn't have helped, however: 在您的特定情况下,正如您在评论中指出的那样,shellcheck.net并没有帮助,但是:

(...) as a conditional passed to if is valid in principle, for executing a command whose exit code to test (although enclosing in (...) is typically not needed for that, because all that does is run the command in a subshell ). (...)作为条件传递给if 有效的原则,执行其退出代码来测试( 命令虽然封闭在(...)通常不需要 ,因为所有不运行在命令一个subshel​​l )。

By contrast, you were looking to evaluate an expression , which is what syntax [[ ... ]] is for - see the Bash manual online or section CONDITIONAL EXPRESSIONS in man bash . 相比之下,您希望评估一个表达式 ,这就是语法[[ ... ]]含义-请参见在线Bash手册man bash CONDITIONAL EXPRESSIONS部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM