【问题标题】:Combine two Bash while loop statements结合两个 Bash while 循环语句
【发布时间】:2017-04-26 22:11:56
【问题描述】:

我试图在一个 while 循环中组合 2 个不同的逻辑语句,但是无法正确地获取逻辑,以便可以在 same 循环中评估 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 语句,但此时我很困惑。基本上作为脚本的一部分,当要求用户输入用户名而不退出脚本直到输入有效值时,我希望将这两个逻辑语句组合起来。

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 我在第 7 行遇到了 binary operator expected,但使用双精度 [ 成功了,谢谢。
    【解决方案2】:

    您可以将条件检查从 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
    

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

    【讨论】:

    • 感谢您重新安排此内容并添加 cmets。看到它以这种方式构建对我来说更有意义。速记代码有效,但这种方式也有效。注意你和 Ipor 提到的大写变量。
    猜你喜欢
    • 2014-01-21
    • 2013-03-26
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    相关资源
    最近更新 更多