Changing UIDs and GIDs for a user
Have you ever needed to change the UID and/or GID of a user and all the associated files on a Linux system but unsure on how and what impact it would have. Don't panic the procedure is pretty simple.
Procedure
Say, I want to change UID from 1000 to 2000 and GID from 3000 to 4000 on Linux. How do I make such change for belonging files and directories?
The procedure is pretty simple:
- Assign a new UID to the user using the
usermod
command. - Assign a new GID to the group using the
groupmod
command. - Use the
chown
andchgrp
commands to change old UID and GID to the new UID and GUI respectively. Note: You can automate this withfind
command.
Commands
Here's the commands to run as root to change the uid
and gid
for a given user:
usermod -u <NEWUID> <LOGIN> groupmod -g <NEWGID> <GROUP> find / -user <OLDUID> -exec chown -h <NEWUID> {} \; find / -group <OLDGID> -exec chgrp -h <NEWGID> {} \; usermod -g <NEWGID> <LOGIN>
usermod
and groupmod
simply change the UID and GID for their respective named counterpart usermod also changes the UID for the files in the homedir but naturally we can't assume the only place files have been created is in the user's homedir.
The find
command recurses the filesystem from / and changes everything with uid of OLDUID to be owned by NEWUID and everything with gid of OLDGID changes to group NEWGID
Example
As an example, we will use the following:
Username/Group | oldUID | newUID | oldGID | newGID |
---|---|---|---|---|
mchurchi | 84838 | 9001 | ||
syssup | 157 | 2001 |
Note:All commands are run as root
user.
- Change UID
# usermod 9001 mchurchi
- Change GID
# groupmod 2001 syssup
- Change ownership to NEWUID
# find / -user 84838 -exec chown -h 9001 "{}" \;
- Change group to NEWGID
# find / -group 157 -exec chgrp -h 2001 "{}" \;
- Change users GID to NEWGID
# usermod -g 2001 mchurchi
Warning: Changing UIDs and GIDs should be done with due care and attention as it could be hazardous to your sanity if it all goes pear-shaped.