结合两个Bash while循环语句 [英] Combine two Bash while loop statements
问题描述
我正在尝试将单个中的两个不同的逻辑语句组合在一起
循环,但是无法正确获取逻辑,因此可以在相同的循环。例如,我有以下2个逻辑语句。
I am trying to combine 2 different logical statements in a single while
loop, but having trouble getting the logic correct so that 2 different checks can be evaluated in the same loop. For example, I have the following 2 logical statements.
确定输入的用户名是否为空如果是要求用户重新输入其他用户名。
Determine if the entered username is blank and if it is ask the user to re-enter a different username.
echo -ne "User Name [uid]$blue:$reset "
read USERNAME
USERNAME=$(echo "$USERNAME" | tr "[:upper:]" "[:lower:]")
while [[ -z "$USERNAME" ]]; do
echo ""
printf "%s\n" "The User Name CAN NOT be blank"
echo ""
echo -ne "User Name [uid]$blue:$reset "
read USERNAME;
USERNAME=$(echo "$USERNAME" | tr "[:upper:]" "[:lower:]")
done
逻辑2
确定读取的用户名是否已存在,是否确实要求用户重新输入用户名。
Logic 2
Determine if the read username already exists and if it does ask the user to re-enter a username.
echo -ne "User Name [uid]$blue:$reset "
read USERNAME
USERNAME=$(echo "$USERNAME" | tr "[:upper:]" "[:lower:]")
$(command -v getent) passwd "$USERNAME" &>/dev/null
while [[ $? -eq 0 ]]; do
echo ""
printf "%s\n" "$USERNAME exists in LDAP"
echo ""
echo -ne "User Name [uid]$blue:$reset "
read USERNAME;
USERNAME=$(echo "$USERNAME" | tr "[:upper:]" "[:lower:]")
$(command -v getent) passwd "$USERNAME" &>/dev/null
done
为了实现上述目标,我尝试过 while
循环和嵌套 if
语句,我只是在这一点上感到困惑。基本上作为脚本的一部分,我希望在要求用户输入用户名而不输入脚本直到输入有效值时,将这两个逻辑语句组合在一起。
For achieving the described goal I have tried while
loops and nested if
statements and am just confused at this point. Basically as part of the script I would like these 2 logical statements to be combined when the user is asked to enter a username without the script exiting until a valid value is entered.
推荐答案
您可以将条件检查从while语句移动到一对if语句。在这种情况下,我还将读取和相关命令移到了循环的顶部。这意味着你在循环之前不需要额外的读取命令。
You could move the conditional check from the while statement to a pair of if statements. In this case, I've also moved the read and related commands to the top of the loop. This means you don't need extra read commands before the loop.
#!/bin/bash
while true; do
echo -ne "User Name [uid]$blue:$reset "
read username;
username=$(echo "$username" | tr "[:upper:]" "[:lower:]")
$(command -v getent) passwd "$username" &>/dev/null
if [[ -z "$username" ]]; then
echo ""
printf "%s\n" "The User Name CAN NOT be blank"
echo ""
continue #Skips the rest of the loop and starts again from the top.
fi
if [[ $? -eq 0 ]]; then
echo ""
printf "%s\n" "$username exists in LDAP"
echo ""
continue #Skips the rest of the loop and starts again from the top.
fi
#If execution reaches this point, both above checks have been passed
break #exit while loop, since we've got a valid username
done
顺便说一句,通常建议避免使用大写变量名,以避免与系统环境变量发生冲突。
As an aside, it's often recommended to avoid uppercase variable names, in order to avoid conflicts with system environment variables.
这篇关于结合两个Bash while循环语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!