结合两个Bash while循环语句

时间:2016-12-12 04:22:07

标签: bash if-statement while-loop logical-operators

我正在尝试在单个while循环中组合2个不同的逻辑语句,但无法正确获取逻辑,因此可以在相同的循环中评估2个不同的检查。例如,我有以下2个逻辑语句。

逻辑1

确定输入的用户名是否为空,是否要求用户重新输入其他用户名。

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

确定读取的用户名是否已存在,以及是否确实要求用户重新输入用户名。

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语句,此时我只是感到困惑。基本上作为脚本的一部分,我希望在要求用户输入用户名而不输入脚本直到输入有效值时,将这两个逻辑语句组合在一起。

2 个答案:

答案 0 :(得分:1)

不要使用大写变量名!

#!/bin/bash
while true; do
    echo -ne "User Name [uid]$blue:$reset "
    read username
    [ -z "$username" ] && echo -e "\nThe User Name CAN NOT be blank\n" && continue
    username=$(tr [:upper:] [:lower:] <<< $username)
    [ -z $(getent passwd "$username") ] && break || echo -e "\n$username exists in LDAP\n"
done

答案 1 :(得分:0)

您可以将条件检查从while语句移动到一对if语句。在这种情况下,我还将读取和相关命令移到了循环的顶部。这意味着在循环之前不需要额外的读取命令。

#!/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

顺便说一句,通常建议避免使用大写变量名,以避免与系统环境变量发生冲突。

相关问题