Search code examples
bashcentossudosudoers

Toggle for adding a user to and removing the user from sudo group?


I know how to add users to the sudo group or how to remove him/her from it:

sudo usermod -aG wheel $1 # $1 represents the username as an argument passed to the command
sudo gpasswd -d $1 wheel 

How do I make it a toggle? If the user is in the sudo group, I'd remove it from the group, otherwise add it. It's useful for temporarily granting sudo privileges.


Solution

  • Use an if that checks whether the user is currently in the group. See also Check if a user is in a group, from which I borrowed this check.

    if [[ " $(id -Gn "$1") " == *" wheel "* ]]; then
        sudo gpasswd -d "$1" wheel
    else
        sudo usermod -aG wheel "$1 "
    fi