在循环语句中结合两个bash



我试图在单个 while循环中结合2个不同的逻辑语句,但是要纠正逻辑,因此可以在 same 循环。例如,我有以下2个逻辑语句。

逻辑1

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

echo -ne "User Name [uid]$blue:$reset "
read USERNAME
USERNAME=$(echo "$USERNAME" | tr "[:upper:]" "[:lower:]")
while [[ -z "$USERNAME" ]]; do
        echo ""
        printf "%sn" "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 "%sn" "$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语句,并且此时感到困惑。基本上,作为脚本的一部分,我希望在要求用户输入用户名的情况下,而无需退出脚本直到输入有效的值时,要组合这两个逻辑语句。

不使用大写变量名称!

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

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

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

最新更新