Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a user to a group without logout/login - Bash script

I searched and could not find this answer anywhere else. Apologies if it's a bit of a noob question for someone not that experienced at scripting.

I'm trying to create a bash script to setup a server with all software needed for an application. In short, when installing docker I need to add the current user to the docker group 'usermod -aG docker ', and from there, pull some containers.

The problem I have is that because I've added the user to a group, they need to be logged out and back in again before they have any permission to do anything later in the script. This of course breaks the script and ends the shell session. Is there a way to log out and back in again within the same script, or do things need to get a little more complicated?

Appreciate anyone's help on this. Hope it's a simple answer for someone.

like image 590
Dean Hutt Avatar asked Mar 22 '18 17:03

Dean Hutt


2 Answers

Use the newgrp command to login to a new group.

The way newgrp works is that it changes the group identification of its caller, analogously to login. The same person remains logged in, and the current directory is unchanged, but calculations of access permissions to files are performed with respect to the new group ID.

So for your case, you’ll use:

# usermod -aG docker user
# newgrp docker

Check your new primary group, it should be docker:

$ id -g
989

Confirm from /etc/group

$ cat /etc/group | grep `id -g`
docker:x:989:jmutai

This should do the trick.

like image 132
Ben Njeri Avatar answered Nov 16 '22 03:11

Ben Njeri


I worked around this issue by setting the setgid flag on the docker binary:

sudo chgrp docker $(which docker)
sudo chmod g+s $(which docker)

The first line changes the group of the docker binary to the docker group. The second line enables the setgid flag, which means when you run this binary your group changes the file's group, which we just set to docker.

This is a security issue because it makes it so that effectively everyone is in the docker group, but I did this inside of a container where the only user is the one that I want to add to the docker group anyway. So this solution is only good for specific cases, but in those cases it seems to work well.

like image 29
adzenith Avatar answered Nov 16 '22 03:11

adzenith