Search code examples
bashmacosdscl

How to create a bash script to delete accounts on mac


I am creating a bash script to delete a user account on a mac.

When I pull up terminal and type the commands

sudo dscl . delete /users/username
sudo rm -rf /users/username

It is successful in deleting the desired account and removing the user files.

However, when I create a bash script to do so...

#!/bin/bash
sudo dscl . delete /users/username
sudo rm -rf /users/username

I get the error

delete: Invalid Path
<dscl_cmd> DS Error: -14009 (eDSUnknownNodeName)

Very strange behavior I haven't been able to figure out, although it is likely a simple mistake.

Edit: In my original script, I was doing looping among other things, but for this post I simplified the problem down to a couple of commands wrapped in a bash script.

Thanks for any help.


Solution

  • I thought I would come back and answer this for anybody who is trying to delete a user profile on macs. The original issue I was having was due to some weird path anomaly local to my machine, but here was that final script. As you can see, I have a hard-coded exclusion list built in for profiles I don't want to delete.

    This could be improved upon, but is a basic way to do it.

    #!/bin/bash
    for d in /users/*/;
    do
        if [ "$d" != "/users/exclusionprofile1/" ] && [ "$d" != "/users/exclusionprofile2/" ]; then
               echo "$d"
               sudo rm -rf "$d"
        fi
    done