Bash – Why does kill not work from script, but does work from terminal

bashdashkillUbuntu

I have the following contrived script to illustrate my issue:

#!/bin/bash
set -eux
sudo sleep 120 &
spid=$!
sleep 1
sudo kill $spid
wait $!

This will print

$ ./test.sh 
+ spid=21931
+ sleep 1
+ sudo sleep 120
+ sudo kill 21931
+ wait 21931

and then hang on wait until the sleep 120 times out. However, when I run sudo kill 21931 from another terminal the sleep process is killed immediately. I expected the sudo kill $spid line in the script to also kill the sleep process immediately. Why doesn't this work and how do I make this work?

(Might be relevant: I see this behaviour bash 4.3.42 and dash 0.5.7 on Ubuntu 15.10.)

Best Answer

The difference could be in the /etc/sudoers file. Maybe your user is allowed to run kill with nopasswd on one machine, but not on the other.

Related Question