user3614014
user3614014

Reputation: 673

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

Upvotes: 0

Views: 43

Answers (2)

sjsam
sjsam

Reputation: 21965

Change

USERS_TO_DELETE="test test2 test3"

to

USERS_TO_DELETE=(test test2 test3)

and

for USER in $USERS_TO_DELETE

to

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

Also

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

should be

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

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295403

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.

Upvotes: 4

Related Questions