user3614014 user3614014 - 5 months ago 10
Linux Question

Shell function exiting early rather than looping through all contents

I'm trying to iterate over a list of users, but this code is terminating after the first deletion. What's wrong here?

#!/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

Answer

Your code is running exec userdel.

The exec keyword [when used in this context, rather than with a redirection list alone] tells the shell to directly use an execv-family syscall to invoke userdel with no preceding fork(). This means that the shell no longer exists -- its process-table entry is directly replaced with that of userdel.

Comments