You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
internal-scripts/user-rename

52 lines
1.2 KiB

#!/bin/sh
# Arguments: old name, new name
if [ $# -lt 3 ]; then
printf '%s\n' "Wrong number of arguments\!" >&2
printf '%s\n' "Usage: user-rename [old name] [new name] [new home]" >&2
exit 1
fi
OLD=$1
NEW=$2
HOME=$3
# Get old home dir (no longer used, keeping around for a bit in case it is needed)
#OLD_HOME=$(grep $OLD /etc/passwd | awk -F: '{print $6}')
# Begin sanity check
if ! id "$OLD" 2>&1 >/dev/null; then
printf '%s\n' "ERROR 11: OLD user name not found: $OLD" >&2
exit 11
fi
if id "$NEW" 2>&1 >/dev/null; then
printf '%s\n' "ERROR 12: NEW user name already exists: $NEW" >&2
exit 12
fi
if [ -d "$HOME" ]; then
printf '%s\n' "ERROR 13: New HOME directory already exists: $HOME" >&2
exit 13
fi
# End sanity check
# Rename user
usermod -l $NEW $OLD || { printf '%s\n' "Error renaming user\!" >&2 && exit 1 }
# Change home dir location
usermod -d $HOME -m $NEW || { printf '%s\n' "Error moving home directory\!" >&2 && exit 1 }
# Check if primary group matches old user name; modify if so
if [ ! "$(id -gn $NEW)" == "$OLD" ]; then
groupmod -n $NEW $OLD || { printf '%s\n' "Error renaming primary group\!" >&2 && exit 1 }
fi
# Done! Print some info and exit
grep $NEW /etc/passwd
id $NEW
exit 0