How to remove a user from all groups?

To remove a user from all groups in Linux, you can use the gpasswd command in combination with a loop to iterate through all groups. Here’s how to do it:

Using a Shell Loop

You can run the following command in the terminal:

for group in $(groups username | cut -d: -f2 | tr -d ' ' | tr ' ' '\n'); do
    sudo gpasswd -d username $group
done

Explanation

  • groups username: Lists all groups the user belongs to.
  • cut -d: -f2: Extracts the group names from the output.
  • tr -d ' ': Removes any leading spaces.
  • tr ' ' '\n': Converts spaces to newlines for easier iteration.
  • gpasswd -d username $group: Removes the user from each group.

Example

To remove a user named bob from all groups, replace username with bob in the command:

for group in $(groups bob | cut -d: -f2 | tr -d ' ' | tr ' ' '\n'); do
    sudo gpasswd -d bob $group
done

Summary

This method effectively removes a user from all groups they belong to. Ensure you have the necessary permissions (usually root) to perform these actions.

0 Comments

no data
Be the first to share your comment!