Hassle Free Way to Kill Sudo'd Jobs

Every now and then I have to run a foreground job under sudo that doesn't want to die when I hit ^C. Then it's a hassle to ^Z, get the pid of the sudo job, and sudo kill that pid.

So I wrote a little script (or a template for scripts) that runs the sudo job in the background (but preserves stdout/stderr) and relies on bash to clean up the job when you ^C the script. Only gotcha with this is that you may have to retype your sudo password when you ^C if your authentication has timed out by the time you get around to killing it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/bin/bash
function cleanup()
{
    sudo kill $job_pid
    wait $job_pid
    exit 0
}
trap cleanup SIGTERM
trap cleanup SIGINT
sudo long_running_foreground_process &
job_pid=$!
wait
Posted on 2009-08-12 by brian in tools .

Comments

I'm embarrassed that I didn't think of this approach before. I've been using a system which was much more complicated, simply because I didn't think things through more carefully. Thanks for sharing.

William L. Dye ("willdye")
2009-10-17 19:56:14
Comments on this post are closed. If you have something to share, please send me email.