Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Create & delete user accounts from the command line on Mac OS X (See related posts)

The following two Bash scripts will interactively prompt for user input to create or delete user accounts on Mac OS X 10.4.11. Use them at your own risk!

1. Create a user account

#!/bin/bash

# cf. Adding a User From the Command Line,
# http://developer.apple.com/documentation/Porting/Conceptual/PortingUnix/additionalfeatures/chapter_10_section_9.html

if [[ "$(/usr/bin/whoami)" != "root" ]]; then printf '\nMust be run as root!\n\n'; exit 1; fi

OPATH=$PATH
export PATH=/usr/bin:/usr/sbin:/bin:/sbin

OIFS=$IFS
export IFS=$' \t\n'

declare sudo=/usr/bin/sudo dscl=/usr/bin/dscl

printf "\e[1mEnter first name\e[m: "
read firstname

# no spaces in names
if [[ -z "$(printf -- "$firstname" | /usr/bin/grep -Eo "^[^[:space:]]+$")" ]]; then
   printf '\nUse a name without spaces! \nPlease, try again!\n\n'
   exit 1
fi

# name must not begin with a number
if [[ -n "$(printf -- "$firstname" | /usr/bin/grep -E "^[[:digit:]]")" ]]; then
   printf '\nName must not begin with a number! \nPlease, try again!\n\n'
   exit 1
fi


# make sure the user name is unique
new_user="$(/usr/bin/dscl . -search /Users name "$firstname" 2>/dev/null)"

if [[ -z "$new_user" ]]; then
  new_user="$firstname"               
else
  printf "\nUser name already exists: $firstname \nPlease, modify your name and try it again\x21\n\n"       # cf. man ascii for \x21
  exit 1
fi 


# make sure the user's primary group name is unique 
# note: the user's primary group name is also based on the first name!

new_group="$(/usr/bin/dscl . -search /Groups name "$firstname")"

if [[ -z "$new_group" ]]; then
  new_group="$firstname"             
else
  printf "\nThe user's primary group name already exists: $firstname\x21 \nPlease, try again\x21\n\n"
  exit 1
fi 


# make sure there is no (file or) home directory of the same name already
if [[ -e "/Users/$new_user" ]]; then
  printf "\nUser $new_user already exists at /Users/$new_user\x21 \nPlease, try again\x21\n\n"
  exit 1
fi


# last name

printf "\e[1mEnter last name\e[m: "
read lastname

# no spaces in names
if [[ -z "$(printf -- "$lastname" | /usr/bin/grep -Eo "^[^[:space:]]+$")" ]]; then
   printf '\nUse a name without spaces! \nPlease, try again!\n\n'
   exit 1
fi

# name must not begin with a number
if [[ -n "$(printf -- "$lastname" | /usr/bin/grep -E "^[[:digit:]]")" ]]; then
   printf '\nName must not begin with a number! \nPlease, try again!\n\n'
   exit 1
fi


# enter password

printf "\e[1mEnter password\e[m: "
stty_orig=$(/bin/stty -g) 
pass=''
blank='false'

while [[ "$blank" != "true" ]]; do

   /bin/stty -icanon -echo

   c=$(/bin/dd bs=6 count=1 2> /dev/null)

   # Check for a CR.
   if [[ -z "$(printf -- "$c" | /usr/bin/tr -d "\r\n")" ]]; then
      blank='true'
   else
      /bin/stty echo
      printf "*"
      pass="$pass$c"
      /bin/stty -echo
   fi
done

/bin/stty icanon echo
/bin/stty "$stty_orig"
passwd1="$pass"
printf "\n"


# check minimum password length: 6
if [[ -z "$(printf -- "$passwd1" | /usr/bin/grep -Eo "^([[:alnum:]]|[[:punct:]]){6,}$")" ]]; then
   printf '\nUse at least 6 characters (alphanumeric, punctuational) for your password! \nPlease, try again!\n\n'
   exit 1
fi


# confirm password

printf "\e[1mConfirm password\e[m: "
stty_orig=$(/bin/stty -g) 
pass=''
blank='false'

while [[ "$blank" != "true" ]]; do

   /bin/stty -icanon -echo

   c=$(/bin/dd bs=6 count=1 2> /dev/null)

   # Check for a CR.
   if [[ -z "$(printf -- "$c" | /usr/bin/tr -d "\r\n")" ]]; then
      blank='true'
   else
      /bin/stty echo
      printf "*"
      pass="$pass$c"
      /bin/stty -echo
   fi
done

/bin/stty icanon echo
/bin/stty "$stty_orig"
passwd2="$pass"
printf "\n"


if [[ "$passwd1" != "$passwd2" ]]; then
   printf '\nPasswords do not match. \nPlease, try again!\n\n'
   exit 1
else
   printf '\nPassword confirmation was successful!\n\n'
fi



# get unique id numbers (uid, gid) that are greater than 500
unset -v i new_uid new_gid idvar
declare -i new_uid=0 new_gid=0 i=500 idvar=0

while [[ $idvar -eq 0 ]]; do 
   i=$[i+1]
   if [[ -z "$(/usr/bin/dscl . -search /Users uid $i)" ]] && [[ -z "$(/usr/bin/dscl . -search /Groups gid $i)" ]]; then
      new_uid=$i
      new_gid=$i
      idvar=1
      #break
   fi
done

if [[ $new_uid -eq 0 ]] || [[ $new_gid -eq 0 ]]; then printf 'Getting unique id numbers (uid, gid) failed!\n'; exit 1; fi

# old version
# get unique id numbers (for uid, gid) by increasing the highest id number already in use by 1
#new_uid=$(($(/usr/bin/dscl . -list /Users uid | /usr/bin/awk '{print $NF;}' | /usr/bin/sort -n | /usr/bin/tail -n 1) + 1))
#new_gid=$(($(/usr/bin/dscl . -list /Groups gid | /usr/bin/awk '{print $NF;}' | /usr/bin/sort -n | /usr/bin/tail -n 1) + 1))

# make sure $new_uid and $new_gid are equal
#if [[ $new_uid -ne $new_gid ]]; then
#   if [[ $new_uid -gt $new_gid ]]; then new_gid="$new_uid"; else new_uid=$new_gid; fi
#fi



# check once again ...

if [[ $new_uid -eq $new_gid ]] && [[ "$new_user" == "$firstname" ]] && [[ "$new_group" == "$firstname" ]]; then

# create the user's primary group
$sudo /usr/sbin/dseditgroup -o create -r "$firstname $lastname" -i $new_gid "$new_group"
$sudo $dscl . -append "/Groups/$new_group" passwd "*"

$sudo $dscl . -create "/Users/$new_user"
$sudo $dscl . -append "/Users/$new_user" RealName "$firstname $lastname"
$sudo $dscl . -append "/Users/$new_user" NFSHomeDirectory "/Users/$new_user"
###$sudo $dscl . -append "/Users/$new_user" NFSHomeDirectory "/Local/Users/$new_user"
$sudo $dscl . -append "/Users/$new_user" UserShell /bin/bash   
$sudo $dscl . -append "/Users/$new_user" PrimaryGroupID $new_gid
$sudo $dscl . -append "/Users/$new_user" UniqueID $new_uid
$sudo $dscl . -append "/Users/$new_user" hint ""
$sudo $dscl . -append "/Users/$new_user" comment "user account \"$firstname $lastname\" created: $(/bin/date)"
$sudo $dscl . -append "/Users/$new_user" picture "/Library/User Pictures/Animals/Butterfly.tif"
$sudo $dscl . -append "/Users/$new_user" sharedDir Public
$sudo $dscl . -passwd "/Users/$new_user" "$passwd1"

# add some other properties that are usually set (Mac OS X 10.4)
$sudo $dscl . -append "/Users/$new_user" _shadow_passwd ""
$sudo $dscl . -append "/Users/$new_user" _writers_hint "$new_user"
$sudo $dscl . -append "/Users/$new_user" _writers_real_name "$new_user"

$sudo $dscl . -append "/Groups/$new_group" GroupMembership "$new_user"      # add new user to the user's primary group
#$sudo /usr/sbin/dseditgroup -o edit -a "$new_group" -t user "$new_user"

$sudo $dscl . -append /Groups/staff GroupMembership "$new_user"             # test: add new user to group staff

# add the new user to the admin group (Mac OS X 10.4)
# This should be part of a separate admin user account shell script or 
# at least require an additional user input prompt at the beginning!
#$sudo $dscl . -append /Groups/admin GroupMembership "$new_user"
#$sudo $dscl . -append /Groups/appserverusr GroupMembership "$new_user"
#$sudo $dscl . -append /Groups/appserveradm GroupMembership "$new_user"

# log out after running the script to see the new user account has been created
$sudo /usr/sbin/createhomedir -l -u "$new_user"

else

   printf "\nConfiguration of user account: $firstname failed\x21 \nPlease, try again\x21\n\n"
   exit 1

fi


printf "\nUser account:  $firstname  successfully created\x21 \nYou can now log in to your new user account\x21\n\n"

export IFS=$OIFS
export PATH=$OPATH

exit 0


#---------------------------


# test
dscl . list /Users
dscl . -read /Users/<firstname>

dscl . list /Groups
dscl . -read /Groups/<firstname>
dscl . list /Groups GroupMembership



2. Delete a user account


#!/bin/bash

# cf. http://www.macos.utah.edu/documentation/authentication/dscl.html

if [[ "$(/usr/bin/whoami)" != "root" ]]; then printf '\nMust be run as root!\n\n'; exit 1; fi

OPATH=$PATH
export PATH=/usr/bin:/usr/sbin:/bin:/sbin

OIFS=$IFS
export IFS=$' \t\n'

declare sudo=/usr/bin/sudo

printf "\e[1mDelete user account\e[m: "
read user

if [[ -z "$user" ]]; then printf '\nNo user specified! Please, try again!\n\n'; exit 1; fi

# make sure the user exists
usertest="$(/usr/bin/dscl . -search /Users name "$user" 2>/dev/null)"

if [[ -z "$usertest" ]]; then printf "\nUser does not exist: $user\n\n"; exit 1; fi 


# get user's group memberships
groups_of_user="$(/usr/bin/id -Gn $user)"

if [[ $? -eq 0 ]] && [[ -n "$(/usr/bin/dscl . -search /Groups GroupMembership "$user")" ]]; then 
   # delete the user's group memberships
   for group in $groups_of_user; do
      $sudo /usr/bin/dscl . -delete "/Groups/$group"  GroupMembership "$user"
      #$sudo /usr/sbin/dseditgroup -o edit -d "$user" -t user "$group"           
   done
fi


# delete the user's primary group
if [[ -n "$(/usr/bin/dscl . -search /Groups name "$user")" ]]; then
   $sudo /usr/sbin/dseditgroup -o delete "$user"
fi

# if the user's primary group has not been deleted ...
if [[ -n "$(/usr/bin/dscl . -search /Groups name "$user")" ]]; then
printf "
   \e[1mWarning\e[m:
   The group memberships of the user \e[1m$user\e[m have been deleted\x21
   groups_of_user: $groups_of_user
   The user's primary group \e[1m$user\e[m, however, has not been deleted\x21
   Please, try again\x21
   Exiting ...\n
"
  exit 1
fi


# find the GeneratedUID of the user and remove the password hash file 
# from /private/var/db/shadow/hash/<GeneratedUID>
# sudo ls -a /private/var/db/shadow/hash
# sudo ls -l /private/var/db/shadow/hash/<GeneratedUID>

guid="$(/usr/bin/dscl . -read "/Users/$user" GeneratedUID | /usr/bin/awk '{print $NF;}')"

if [[ -f "/private/var/db/shadow/hash/$guid" ]]; then
   $sudo /bin/rm -f /private/var/db/shadow/hash/$guid
fi


# delete the user
$sudo /usr/bin/dscl . -delete "/Users/$user"

# make a backup
if [[ -d "/Users/$user" ]]; then
   $sudo /usr/bin/ditto -rsrc -c -k "/Users/$user" "/Users/${user}-archive-$(/bin/date).zip"
fi

# remove the user's home directory
if [[ -d "/Users/$user" ]]; then
   $sudo /bin/rm -rf "/Users/$user"
fi

export IFS=$OIFS
export PATH=$OPATH

exit 0




Comments on this post

cb0 posts on Apr 08, 2008 at 05:30
Real nice script --- but will somebody Please please please explain what the $ means in:
IFS=$' \t\n'

hanks ... CB0
jv posts on May 08, 2008 at 15:37
man bash:

"
QUOTING
...
Words of the form $'STRING' are treated specially. The word expands to STRING, with backslash-escaped
characters replaced as specifed by the ANSI C standard. Backslash escape sequences, if present, are
decoded as follows:
...
\n newline
...
\t horizontal tab
...

The expanded result is single-quoted, as if the dollar sign had not been present.

A double-quoted string preceded by a dollar sign ($) will cause the string to be translated according to the
current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and
replaced, the replacement is double-quoted.
"

opi posts on Jan 16, 2010 at 13:02

I would like to thank you for the efforts you have made in writing this
article. I am hoping the same best work from you in the future as well. In
fact your creative writing abilities has inspired me to start my own
BlogEngine blog now. Really the blogging is spreading its wings rapidly.
Your write up is a fine example of it……………………………….
Bidet Toilet Seat

You need to create an account or log in to post comments to this site.