Users & Groups
Linux users + groups: id, useradd, usermod, groups, chown, sudoers. The foundation of file permissions and process identity.
Linux — users + groups
EXAMPLE
# ===== Who am I ===== whoami # username id # uid, gid, groups id -u # numeric uid id -gn # primary group name groups # list of groups # ===== List users + groups ===== cat /etc/passwd # one line per user (legacy file) cat /etc/group # groups getent passwd alex # better: works with LDAP / NIS too getent group docker # ===== Create + modify users ===== sudo useradd -m -s /bin/bash alex # -m: create home dir; -s: shell sudo passwd alex # set password sudo usermod -aG docker alex # add to 'docker' group (don't drop existing!) sudo usermod -L alex # lock account sudo userdel -r alex # delete + home dir # Verify: groups alex # ===== Groups ===== sudo groupadd dev sudo groupmod -n developers dev # rename sudo groupdel old # Add multiple users to a group: sudo gpasswd -a alex docker sudo gpasswd -d alex docker # ===== Ownership ===== chown alex file.txt chown alex:developers file.txt chown -R alex:developers project/ # Permissions: chmod 644 file.txt # rw-r--r-- chmod 755 dir # rwxr-xr-x chmod g+w file.txt # add group write # Numeric: r=4 w=2 x=1; 7=rwx 6=rw- 5=r-x 4=r-- # ===== sudo ===== sudo -i # interactive root shell sudo -u alex -i # shell as 'alex' sudo -k # invalidate cached creds # Configure who can sudo: sudo visudo # edits /etc/sudoers safely (validates syntax) # Add to /etc/sudoers.d/<name>: %developers ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart myapp # ===== Effective uid / setuid ===== # Programs marked setuid run as the file owner regardless of caller. ls -l /usr/bin/passwd # -rwsr-xr-x ... root (setuid root) # Avoid creating new setuid programs unless absolutely necessary. # ===== Sessions ===== who # logged-in users w # who + what last # login history # ===== Patterns to internalise ===== # - Always 'usermod -aG' (append) when adding groups; 'usermod -G' REPLACES # - Use visudo for sudoers edits; do NOT edit /etc/sudoers directly # - Groups for permissions, not individual ACLs (manage at scale) # - Drop privileges early in long-running daemons # ===== Pitfalls ===== # - 'usermod -G' (no -a) -> drops user from all OTHER groups # - chmod 777 -> world-writable; almost always wrong # - Adding users to 'sudo' group casually -> wide blast radius # - Forgetting to log out + back in after adding to a group (active sessions don't see new groups)
Why it matters
Users + groups are the identity layer. id, useradd, usermod -aG, getent, chown, visudo. Use groups to grant permissions, log out after group changes, and always append (-a) when modifying group membership. The discipline keeps multi-user systems manageable.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…