我试图迭代用户列表,但此代码在第一次删除后终止。这里有什么问题?
#!/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
答案 0 :(得分:4)
您的代码正在运行exec userdel
。
exec
关键字[在此上下文中使用时,而不是单独使用重定向列表]告诉shell直接使用execv
- 系列调用来调用userdel
而不使用前一个fork()
。这意味着shell不再存在 - 其进程表条目直接替换为userdel
的条目。
答案 1 :(得分:0)
更改
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