Skip to content

Instantly share code, notes, and snippets.

@aji
Created April 16, 2012 04:17
Show Gist options
  • Save aji/2396321 to your computer and use it in GitHub Desktop.
Save aji/2396321 to your computer and use it in GitHub Desktop.
userdel implementation using deluser and chroot
#!/bin/sh
# I haven't tested this.
# I don't even know if it works.
# Also, -f is different.
# In this implementation, -f will automatically confirm -r
if [ "$UID" != "0" ]; then
echo "You are not logged in as root. Cannot continue."
exit 1
fi
if [ -z "$__CHROOT_USE_ENVIRON" ]; then
FORCE=
REMOVE=
CHROOT=
while getopts "frR:" opt; do
case "$opt" in
f) FORCE="yes" ;;
r) REMOVE="yes" ;;
R) CHROOT="$OPTARG" ;;
\?) echo "Unknown option -$OPTARG ignored" >&2 ;;
:) echo "Option -$OPTARG requires an argument" >&2 ;;
esac
done
USER=${@:$OPTIND}
else
if [ -z "$__CHROOT_FORCE" -o -z "$__CHROOT_REMOVE" -o -z "$__CHROOT_USER" ]; then
echo "__CHROOT_USE_ENVIRON, but missing environment!" >&2
exit 1
fi
FORCE="$__CHROOT_FORCE"
REMOVE="$__CHROOT_REMOVE"
USER="$__CHROOT_USER"
fi
if [ -n "$CHROOT" ]; then
if [ -d "$CHROOT" ]; then
export __CHROOT_FORCE=$FORCE
export __CHROOT_REMOVE=$REMOVE
export __CHROOT_USER=$USER
export __CHROOT_USE_ENVIRON=yes
exec chroot "$CHROOT" $0
else
echo "$CHROOT is not a directory" >&2 ;;
fi
exit 1
fi
# Grab their home and mail dir
USER_HOME=$( grep "^$USER" /etc/passwd | cut -d: -f6 )
# Delete the user
deluser $USER
# Remove their home dir
if [ -n "$REMOVE" ]; then
DO_REMOVE=
if [ -z "$FORCE" ]; then
printf "Are you sure you want to rm -rf $USER_HOME? (y/N) "
read $confirm
if [ "$confirm" != "y" -o "$confirm" != "Y" ]; then
echo "Not removing directory"
else
DO_REMOVE=yes
fi
else
DO_REMOVE=yes
fi
[ -n "$DO_REMOVE" ] && rm -rf $USER_HOME
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment