Until user input equals something do

2020-02-10 04:30发布

问题:

So somebody showed me how to use condition(s) to test if a user had typed input for a password. I wanna take a their example a step further and use a loop (at least thats what I think it's call).

Here is their example:

read -s -p "Enter new password: " NEWPASS

if test "$NEWPASS" = ""; then
    echo "Password CAN NOT be blank re-run sshd_config"
    exit 1;
fi

Instead of exiting the script I want it to keep asking for the input until there is some.

I wanna make a statement like this but I was doing it wrong: (Now using top example)

The user is given a chance to enter new password and fill the variable value.

read -s -p "Enter new password:" NEWPASS
echo ""

The next portion checks the variable to see if it contains a value, while the value is null it request the user to fill the value indefinitely. ( a loop)

while [[ -z "$NEWPASS" ]]; do
echo ""
echo "Password CAN NOT be blank"
echo ""
read -s -p "Enter new password:" NEWPASS;
echo ""
done

This line searches a file containing a set of variables used by another file. It then searches the file for a line containing PASS=.* (.* meaning anything) then writes PASS=$NEWPASS ($NEWPASS being variable)

sed -i -e"s/^PASS=.*/PASS=$NEWPASS/" /etc/sshd.conf   

Thank you for all the help, I'm going to use this and learn from it.

回答1:

This while loop should work:

while [[ -z "$NEWPASS" ]]
do
  read -s -p "Enter new password: " NEWPASS
done


回答2:

while read -s -p 'Enter new password: ' NEWPASS && [[ -z "$NEWPASS" ]] ; do
 echo "No-no, please, no blank passwords!"
done