

The 2>/dev/null redirect the stderr of the while loop to the void, so error messages generated by any commands inside the loop will be discarded.

The & operator puts the whole while loop into the background, running it as a child process. Notice that this version differs from the one of the linked gist: it runs sleep 60 first, and then sudo -nv. While true do sleep 60 sudo -nv done 2>/dev/null &: Update the existing sudo security credentials repeatedly. If the next sudo runs too soon, it won't know it because the credentials are not saved yet, thus will ask for the password again. Sleep 1: Delay for a little bit so that security credentials are effectively saved. If the password is not correct, exit with the code returned by sudo. Sudo -v || exit $?: Ask for the password up-front and cache the security credentials, but do not run a command. Trap "exit" INT TERM trap "kill 0" EXIT: This will take down the whole process tree on exit or SIGINT / SIGTERM.

sudoping.shīase on the gist provided by Gregory Perkins and my experience, here's my one-liner: trap "exit" INT TERM trap "kill 0" EXIT sudo -v || exit $? sleep 1 while true do sleep 60 sudo -nv done 2>/dev/null & Sudo echo "Sudo pinging in PID = $SUDO_PID"Īgain, the echo's are extraneous. Maybe this can provide some perspective.Įcho "Stopping sudo ping in PID = $SUDO_PID"Įcho "Already sudo pinging in PID = $SUDO_PID" I liked michael_n's answer, but had the most irrational desire not to use a temp file. (note: the pid is put into the tmp file, just so you can easily kill it. Trap 'rm -f $sudo_stat >/dev/null 2>&1' 0Įcho "running setup $$. (An install script usually does this, anyway.)įor example (remove the 'echo' statements to use this these just show it "working"): #!/bin/bashĮcho "= running script $$ ="

So there has to be some type of communication between the two processes tmp files are fine for this, and they can easily be cleaned up after the script runs, too. You can setup a loop that runs in the background to periodically execute "sudo -v", the trick of course is getting the loop to cleanly terminate when your script terminates.
