Killing a shell script running in background

To improve, use killall, and also combine the commands:

ps -aux | grep script_name
killall script_name inotifywait

Or do everything in one line:

killall `ps -aux | grep script_name | grep -v grep | awk '{ print $1 }'` && killall inotifywait

List the background jobs using

# jobs

Then choose the the prior number of job and run

example

# fg 1 

enter image description here

will bring to foreground.

Then kill it using CTRL+C or easier way to find the PID of script using

ps -aux | grep script_name

enter image description here

Then kill using pid

sudo kill -9 pid_number_here

You can use ps+grep or pgrep to get the process name/pid; later use killall/pkill to kill process name or use kill to kill pid. All of the followings should work.

killall $(ps aux | grep script_name | grep -v grep | awk '{ print $1 }') && killall inotifywait
(ps -ef | grep script_name | grep -v grep | awk '{ print $1 }' | xargs killall) && killall inotifywait
(ps -ef | grep script_name | grep -v grep | awk '{ print $2 }' | xargs kill) && killall inotifywait
(pgrep -x script_name | xargs kill) && pkill -x inotifywait
pkill -x script_name && pkill -x inotifywait

The most important thing is that you should make sure you only kill the exact process(es) that you are hoping to kill.

pkill/pgrep matches a pattern rather than the exact name, so is more dangerous; here -x is added to match the exact name.

Also, when using pgrep/pkill you may need

  • -f to match the full command line(like ps aux does)
  • -a to also print the process name.