I\'ve made a simple bash script that need to keep it\'s super-user privileges throughout the script. Unfortunately, but understandable the script looses its sudo
Working strictly within a script (and not editing the sudoers file or calling the script via sudo ./script.sh
), here's what I think the cleanest method is.
startsudo() {
sudo -v
( while true; do sudo -v; sleep 50; done; ) &
SUDO_PID="$!"
trap stopsudo SIGINT SIGTERM
}
stopsudo() {
kill "$SUDO_PID"
trap - SIGINT SIGTERM
sudo -k
}
Basically, this defines a pair of functions for enabling and disabling sudo mode. Calling startsudo
before running your sudo-using code authenticates with sudo, forks a background sudo-refreshing loop, saves the loop's PID, and sets a signal trap to stop sudo mode when Ctrl+C is pressed. Calling stopsudo
kills the loop, clears the signal trap, and invalidates the earlier authentication with sudo.
After copying these functions into your script, use them like this.
startsudo
echo "Sudo mode is active."
# whatever you want to do with sudo
stopsudo
I would like to thank @karl for the simplicity of inlining the sudo-refreshing loop and @sehe for pointing out that a signal trap should be used to kill the loop if it isn't killed normally. Both of these ideas improved my btrfs backup script, which uses a sudo-refreshing loop to avoid re-prompting the user after a subvolume's backup takes longer than sudo's timeout.