Skip to content
shellhacks.dev
Linux

Always use -a with -G

Add a user to a group with usermod -aG. Without -a the -G option replaces the whole supplementary group list, and the user silently loses every other group.

1 min read
Summarize in AI

A user needs one more group, and usermod -G looks like the way to add it, until the other groups disappear.

Shell
groupadd docker-demo; groupadd web-demo
useradd -M -s /usr/sbin/nologin deploy
usermod -aG docker-demo deploy
usermod -aG web-demo deploy
id -nG deploy
usermod -G docker-demo deploy
id -nG deploy
Text
deploy docker-demo web-demo
deploy docker-demo

-G sets the complete list of supplementary groups, and -a makes it append to the list instead. The usermod manual says -a is only valid together with -G. The first two runs append and keep both groups. The last run leaves out -a, so the user ends up in the primary group and docker-demo alone.

A running session does not see a new group until the user logs in again, or starts a new login shell with newgrp or su -. On systems that manage groups through LDAP or SSSD, usermod only touches local groups. gpasswd -a user group is an equivalent that cannot drop groups by mistake.

Share

More snippets

Linux

Get a process's command line

Read a running process's full command line from /proc/PID/cmdline. The arguments are separated by NUL bytes, so split them with xargs -0 and not tr.

1 min read
Linux

Run a command with a clean environment

Run a command with an empty environment using env -i, then add back only the variables you pass. It reproduces what cron or a minimal container sees.

1 min read
Linux

Convert a date string to a timestamp

Convert a date string to a Unix timestamp with GNU date -d 'string' +%s. The zone is the one in TZ unless the string names one, so set it explicitly.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.