A quick guide on how to copy group member ship in Linux to another user. Which can be useful when setting up new users on a Linux machine to make sure that users. It is also a way to find out what groups a user is a member of.

Part 1 - Get a list of groups

To get a list of groups as user is a member of can be done by reading the /etc/group file and doing a little bit of processing. This can be done using the following command.

grep -E "(:|,)originaluser(:,|$)" /etc/group|cut -f1 -d:

The complex expression above is built to match specific username in each line of the file. Of which there is 3 different cases ":" ",," ",". So we search for the specific username beginning with a ":" or a "," and also ending in a "," or a "$" which is a newline. Then it cuts on the first field using ":" as a separator.

This will output a list of group that "" is a member of.

Part 2 - Add another user to the same list of groups

Since we know that addgroup can be used to add a user to a group by doing "addgroup " then we can expand the above to add a username to each group in the list like this

for i in `grep -E "(:|,)<username>(:,|$)" /etc/group|cut -f1 -d:` ; do
    addgroup mynewuser $i
done

This will then make sure that the user mynewuser is a member of all the same groups that originaluser is.

You should take care using the above as you may give somebody access well beyond what you thought you might have by giving them access to additional groups.



Did You find this page useful?

Yes No



Last Modified: 23 February 2017

Releated Posts


2013-03-01 - Linux - What and how to kill a zombie process
2013-02-14 - Linux - Getting sshfs to work
2012-12-12 - Linux - List / Copy group membership for users
2012-12-08 - Linux - ssh key authentication
2012-12-04 - Linux - sudo without a password
2012-10-13 - Rasberry Pi - Alternative method to play video without omx gstreamer element
2012-10-10 - How to run tcpdump as root
2012-07-13 - Linux - Killing all processes for a specific user
2012-04-05 - Using gdb to debug a core file
2012-01-16 - Linux - Color Coding The Bash Prompt
2012-01-14 - Linux - Automatically set the DISPLAY environment variable in SSH connection
2012-01-06 - Adding extra swap space to linux