Search code examples
linuxbashshellsudo

Script to check if user belongs to sudo group


I think I'm fairly close to checking if a user belongs to the sudo group in Ubuntu, then add a line to the sudoers file. Except when I look in the sudoers file, I see:

$IDUSER ALL=NOPASSWD: /usr/local/sbin/myscript

instead of that users name, eg.

bob ALL=NOPASSWD: /usr/local/sbin/myscript

Here is what I have:

#! /bin/sh

set -e

IDUSER=$(grep -Po '^sudo.+:\K.*$' /etc/group)

if [ `id -u $IDUSER 2>/dev/null || echo -1` -ge 0 ]; then 
    echo '$IDUSER ALL=NOPASSWD: /usr/local/sbin/myscript' >> /etc/sudoers

else
    echo "Script failed..."
fi

Ideally, I'd like to add all users in the sudo group to the sudoers file.

Thank you.


Solution

  • In single quotes ', bash variables don't get expanded. Use double quotes " instead in the line with echo.

    If you're just trying to let users in the group sudo run this command, though, just add the line:

    %sudo ALL=NOPASSWD: /usr/local/sbin/myscript
    

    to the /etc/sudoers file. The % sign denotes a group, here.