How to (Correctly) Change the UID and GID of a user/group in Linux

Changing the UID and GID of a user might seem a trivial task to most of the system admins. But it’s not so trivial and it involves a lot more changes in the backend. In this post, we have outlined the exact steps to change the UID and GID of a user “user01”.

Username: user01
Group: group01
Existing UID: 800
Existing GID: 700
New UID: 900
New GID: 600

Pre-requisites

1. Make sure the user for which UID and GID is to be changed is currently not having any active process running in the system. To check the same use “ps” command. For example:

# ps -ef | grep user01
# ps -ef | grep 800
Note: In the “ps -ef” command UID are displayed. So make sure you grep for UID as well as the username for the user.

2. Take the backup of important files where UID and GID related information is stored. i.e. /etc/passwd and /etc/group.

# cp -p /etc/passwd /etc/passwd.bkp
# cp -p /etc/group /etc/group.bkp

3. Verify the exisitng UID and GID of the user using the “id” command:

# id user01
uid=800(user01) gid=700(group01) groups=700(group01)

Modifying the UID and GID of the user and group

Once you have taken necessary backups and command outputs we can go ahead and change the UID and GID.

1. First change the GID of the group, group01:

# groupmod -g 600 group01

2. Next, change the UID as well and GID of the user, user01:

# usermod -u 900 -g 600 user01

3. Verify the new UID and GID of the user:

# id user01
uid=900(user01) gid=600(group01) groups=600(group01)

Caveats

1. If there are multiple users in the group “group01”, after changing the GID of the group you will have to modify the other users as well along with the user01 as shown above.

2. Once you have changed the UID and GID, you will have to change the permissions of the files owned by the user/group as well. But the chown command also resets the SETUID and SETGID of the files, so you will need to manually change the permissions of these files later on. To find such files:

# find / -uid 900 -perm /6000 -ls
# find / -gid 900 -perm /6000 -ls

3. To find the files owned by user01 and group01 and to change their permissions:

# find / -uid 800 -exec chown -v -h 900 '{}' \;
# find / -gid 700 -exec chgrp -v 600 '{}' \;

The -h option is used to change the permissions of symbolic links as well.

Related Post