shell 函数提前退出,而不是遍历所有内容



我正在尝试迭代用户列表,但此代码在第一次删除后终止。这是怎么回事?

#!/bin/bash
       function delete_users() {
          echo "Deleting system users"
          local USERS_TO_DELETE="test test2 test3"
          for USER in $USERS_TO_DELETE
             do
                local USER_EXIST=$(getent passwd ${USER})
                   if [ -z "$USER_EXIST" ]
                      then
                         echo "User $USER does not exist"
                   elif [ -n "$USER_EXIST" ]
                      then
                         exec userdel $USER
                         echo "Successfully deleted $USER account"
                    fi
              done
          return 0
            }
      delete_users

您的代码正在运行exec userdel .

exec 关键字 [在此上下文中使用时,而不是单独用于重定向列表时] 告诉 shell 直接使用 execv -family syscall 来调用没有前面fork()userdel。这意味着 shell 不再存在 -- 它的处理表条目直接替换为 userdel 的条目。

更改

USERS_TO_DELETE="test test2 test3"

USERS_TO_DELETE=(test test2 test3)

for USER in $USERS_TO_DELETE

for USER in "${USERS_TO_DELETE[@]}" #Double quote to avoid re-splitting elements though nbd here

exec userdel "$USER" # exec replaces the current shell with a new instance

应该是

if userdel "$USER"  #introduced some error checking 
then
echo "Successfully deleted $USER account"
fi

相关内容

  • 没有找到相关文章

最新更新