Kemin Zhou
Kemin Zhou

Reputation: 6891

How to change my current unix group

I belong to several user groups (say coder, projectmanager, sudo), for some reason I may not be in a particular group. This happens when I am in a particular directory that belong to a particular group where I need the write access to create new files. It is quite annoying that I am in a different group. When I run the groups command, I am listed as in groupA, how do I become groupB?

When I do a search, the top link goes to how to create groups.

Upvotes: 1

Views: 2890

Answers (2)

Adam Katz
Adam Katz

Reputation: 16206

If you're an admin, just do it as root or as a user with the appropriate permissions.

If you're trying to avoid that, you can add yourself to the group. Most systems will let you do that with a simple command:

sudo usermod -a -G newgroup username

Older systems require editing /etc/group. First try sudo vigr ("vi group," much like vipw for the passwd file) and if that isn't present, you may edit it directly via sudo vi /etc/group.

Find the relevant group and append yourself to it. Users are in the last colon-delimited section and are comma-delimited within that section. For example, you can add yourself to the "cdrom" and "games" groups:

Before:

root:x:0:
users:x:100:kemin
cdrom:x:24:
games:x:60:adam

After:

root:x:0:
users:x:100:kemin
cdrom:x:24:kemin
games:x:60:adam,kemin

A very quick programmatic approach —which lacks safeties— could look like:

sudo sed -i '/^games:/s/$/,kemin/; s/:,/:/g' /etc/group

I only added one safety above, which accounts for an empty group (no comma needed). This does not check to ensure you're initially absent from the group, and I didn't use a regex alternation (/^\(games\|cdrom\):/…) because non-GNU sed doesn't support it.

(This may not work on systems that lock /etc/group to vigr. The fact that it's hard to get all the safeties correct is why such locking is justified.)

 

This will not immediately work! You need to log out and log back in, or else sudo as yourself (which is a good way to test without the hassle of logging out), e.g. sudo -u $USERNAME groups, or get a new login through a virtual terminal (Alt+F2) or something like ssh localhost.

Upvotes: 1

Kemin Zhou
Kemin Zhou

Reputation: 6891

The command is actually newgrp. Several other group related commands are:

chdgrp  List groups with title and remaining balance
groups  See groups to which you belong with primary group first
chgrp   Change group ownership of directories and files

Upvotes: 0

Related Questions