Bash – Killing a shell script running in background

bashinotifykillshell

I have written a shell script to monitor a directory using the inotifywait utility of inotifyt-tools. I want that script to run continuously in the background, but I also want to be able to stop it when desired.

To make it run continuously, i used while true; like this:

while true;
do #a set of commands that use the inotifywait utility
end

I have saved it in a file in /bin and made it executable. To make it run in background, i used nohup <script-name> & and closed the terminal.

I don't know how do I stop this script. I have looked at the answers here and a very closely related question here.

UPDATE 1:
On the basis of the answer of @InfectedRoot below, I have been able to solve my problem using the following strategy.
First use

ps -aux | grep script_name

and use sudo kill -9 <pid> to kill the processes.
I then had to pgrep inotifywait and use sudo kill -9 <pid> again for the id returned.

This works but i think this is a messy approach, I am looking for a better answer.

UPDATE 2:
The answer consists of killing 2 processes. This is important because running the script on the command line initiates 2 processes, 1 the script itself and 2, the inotify process.

Best Answer

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
Related Question