Bash 嵌套循环不通过循环迭代

Bash 嵌套循环不通过循环迭代

我在 for 循环中有一个 while 循环,使用 drush 在 drupal 中创建用户帐户,但它没有正确迭代序列。它可以很好地创建帐户或所有域,但 while 循环不会在第一个帐户之后创建用户角色。有人看到我的错误吗?

#add the user
USERLIST=(
        "$USER,page_creator" 
        #"$USER,layout_manager"
        "$USER,page_reviewer" 
        "$USER,landing_page_creator"
        "$USER,landing_page_reviewer"
        "$USER,media_manager"
        "$USER,block_creator"
        #"$USER,site_builder"
        "$USER,block_manager"
    )

count=0

DOMAINLIST=("lmn" "pdq" "xyz")
for SITE in "${DOMAINLIST[@]}"
do
    echo "Creating account for $USER"
    drush "@company-acsf."$SITE ucrt $USER --password="$PW" --mail="$USER"
        while [ "x${USERLIST[count]}" != "x" ]
        do
            count=$(( $count + 1 ))
            IFS=',' read -ra LINE <<< "${USERLIST[count]}"
            USERNAME=${LINE[0]}
            USERROLE=${LINE[1]}     

            if [[ -n "$USERNAME"  && -n "$USERROLE" ]] ; then
                echo "Updating account for $USERNAME with role \"$USERROLE\""
                drush "@company-acsf."$SITE urol "${USERROLE}" $USERNAME
            fi
        done
done
exit 0

答案1

如前所述,该count变量在 for 循环之外初始化,但在第一个 while 循环之后不会重置。另一个问题是count变量增加得太早并且角色page_creator被跳过。密码PW也没有设置,但我猜你只向我们展示了脚本的一部分。

您可以将 while 循环更改为 for 循环,如下所示(以及一些小的改进,请参阅评论):

#!/bin/bash
### ^^^^^^^ add shebang

#add the user
USERLIST=(
        "$USER,page_creator"
        #"$USER,layout_manager"
        "$USER,page_reviewer"
        "$USER,landing_page_creator"
        "$USER,landing_page_reviewer"
        "$USER,media_manager"
        "$USER,block_creator"
        #"$USER,site_builder"
        "$USER,block_manager"
    )

### remove
#count=0
DOMAINLIST=("lmn" "pdq" "xyz")
for SITE in "${DOMAINLIST[@]}"; do

    ### add SITE name to echo
    echo "Creating account for $USER, site \"$SITE\""
    drush "@company-acsf."$SITE ucrt $USER --password="$PW" --mail="$USER"

    ### change while-loop to for-loop
    for ((count=0; count < ${#USERLIST[@]}; count++)); do
    #while [ "x${USERLIST[count]}" != "x" ]
    #do
        ### remove
        #count=$(( $count + 1 ))
        IFS=',' read -ra LINE <<< "${USERLIST[count]}"
        USERNAME=${LINE[0]}
        USERROLE=${LINE[1]}
        if [[ -n "$USERNAME"  && -n "$USERROLE" ]]; then
            echo "Updating account for $USERNAME with role \"$USERROLE\""
            drush "@company-acsf."$SITE urol "${USERROLE}" $USERNAME
        fi
    done
done

### probably not needed, exit status is the status of the last command
#exit 0

留下作为练习:将变量更改为小写并引用所有变量。使用shellcheck.net查找 shell 脚本中的错误。

相关内容