Ashley Ashley - 7 months ago 9
Bash Question

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. I tried using source but it does not give me access to the variables. Here are my parts of my files below:

passwords.txt

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


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.

Answer

The problem is not with sourcing, but with the syntax of your if statement.

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:

 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.

In your specific case, as you point out in a comment, shellcheck.net wouldn't have helped, however:

(...) 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).

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.

Comments