I will introduce several useful commands in Ubuntu to manipulate users and groups.

Group manipulations (3 commands)

  • List all groups: groups
  • Add a new group: groupadd <new group name>
  • Remove a group: groupdel <group name>

User manipulations (5 commands)

  • My username: whoami
  • List all users: cat /etc/passwd
  • Add a new user: adduser <new username>
  • Remove a user: deluser [--remove-home] <user name>. (add --remove-home flag to remove the associated home directory)
  • Change a user's password: passwd <username>

Group-User manipulations (5 commands)

  • Which groups do I (or a user) belong to: groups <username> (omit <username> to specify the current user)
  • List all groups: cat /etc/group
  • Add a user to a group: usermod -aG <group name> <username>
  • Remove a user from a group: deluser <username> <group name>
  • List all members in a group: getent group <group name>. Or members <group name> (required install an additional package with apt install members)

Others

  • Rename a group: sudo groupmod --new-name <new name> <old name>
  • To run a command as a specific user: sudo su -l <username> -s <command>
  • Change ownership: chown [-R] <username> <file1> [<file2> [<file3>]]
  • Change group ownership: chgrp [-R] <group name> <file1> [<file2> [<file3>]]
  • When a user is added to a group, the change does not take effect until the next login. To open a new session with the change effective: newgrp <group name> will start a new shell or newgrp <group name> <<< "<command>" to execute the command and return back to the current shell.