Best practices on using sudo in a bash script

Regarding method 2, it's easier to use a function. For example:

#!/bin/bash

func(){
    echo "Username: $USER"
    echo "    EUID: $EUID"
}

export -f func

func
su "$SUDO_USER" -c 'func'

$SUDO_USER is the sudoer's username. You could also use $(logname) in its place.

Running on my machine:

$ sudo bash test.sh
[sudo] password for wja: 
Username: root
    EUID: 0
Username: wja
    EUID: 1000

By reading man sudoers, one sees:

 PASSWD and NOPASSWD

   By default, sudo requires that a user authenticate him or herself
   before running a command.  This behavior can be modified via the
   NOPASSWD tag.  Like a Runas_Spec, the NOPASSWD tag sets a default for
   the commands that follow it in the Cmnd_Spec_List.  Conversely, the
   PASSWD tag can be used to reverse things.  For example:

   ray     rushmore = NOPASSWD: /bin/kill, /bin/ls, /usr/bin/lprm

   would allow the user ray to run /bin/kill, /bin/ls, and /usr/bin/lprm
   as root on the machine rushmore without authenticating himself. 

Thus, you could allow regular on host machine1 to execute command1 and command2 as root, without password authentication with:

reguser machine1 root = NOPASSWD: /usr/local/command1, /usr/local/command2  

but read each of man -k sudo for details.

Tags:

Bash

Sudo

Su