Skip to content

Instantly share code, notes, and snippets.

@Synchro
Created October 9, 2014 09:00
Show Gist options
  • Save Synchro/1eeb671a462d446dbf03 to your computer and use it in GitHub Desktop.
Save Synchro/1eeb671a462d446dbf03 to your computer and use it in GitHub Desktop.
Shell script to change a numeric UID and all files it owns
#!/bin/bash
# Change a user's UID and all files owned by them everywhere
# Syntax: chuid <from uid> <to uid>
# Example: chuid 1000 1001
# <From uid> must exist; <to uid> must not exist
# usermod will fail if the <from uid> has any running processes
# - stopping them is left to you
# @author Marcus Bointon <https://gist.github.com/Synchro>
set -e
if [ "$#" -ne 2 ]; then
echo "You must provide from and to UIDs"
exit 1
fi
if [ $1 -eq 0 ]; then
echo "Don't change root's UID!"
exit 1
fi
FROMUSER=`getent passwd $1 | cut -d: -f1`
if ! getent passwd "$1" > /dev/null; then
echo "User $1 does not exist"
exit 1
fi
if getent passwd "$2" > /dev/null; then
echo "User $2 exists"
exit 1
fi
#First change the user's uid and all files in their home dir
usermod -u $2 "$FROMUSER"
#Now change all other files belonging to the original UID to them
chown -R $2 --from=$1 /
# If this involved any system users or daemon owners, it's a good idea to reboot now
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment