sudo in non-interactive script
Add your script to the /etc/sudoers
file with the NOPASSWD
attribute, so that it is permitted to run without prompting for a password. You can tie this down to a specific user (or set of users), or allow it to be run with sudo
by anyone on your system.
A sample line for a script called /usr/local/bin/bossy
might look something like this
ALL ALL = (root) NOPASSWD: /usr/local/bin/bossy
And you'd then use something like this
A && sudo bossy && C
For this example I assumed PATH
includes /usr/local/bin
. If not, then just use the full path to the script, i.e. sudo /usr/local/bin/bossy
I think the best thing that you can do is launch the script with sudo
and then launch the processes you want to run as a normal user explicitly with su user
or sudo -u user
:
#!/usr/bin/env bash
## Detect the user who launched the script
usr=$(env | grep SUDO_USER | cut -d= -f 2)
## Exit if the script was not launched by root or through sudo
if [ -z $usr ] && [ $UID -ne 0 ]
then
echo "The script needs to run as root" && exit 1
fi
## Run the job(s) that don't need root
sudo -u $usr commandA
## Run the job that needs to be run as root
commandB