Here is a shell script that will allow you to kill a script if it is already running
#!/usr/bin/env bash
ps -ef | grep $1 | awk '{print $2}' | xargs kill -9
Supply the name of the script as the first parameter and it will look to see if there is a matching process, and if so, kill it.
Obviously this is something you need to be careful with!
Code Breakdown
- ps -ef – this gets our list of running processes, along with the command that is running and the associated process IDs. We need to match the process against our supplied keyword ($1) and get the ID back.
- Grep looks the text output by the PS for the keyword supplied on the command-line ($1).
- Awk takes the columns of text from the Grep search and extracts the second column, which is our process IDs.
- Xargs allows us to iterate over a list (of IDs in this case) and run a command against each entry. This is where the killing happens.
- Kill -9 means “nuke from orbit” 🙂
I am assuming if you want to do this you really want to do this. If it is not such a priority then don’t use -9 and give the process a chance to end gracefully.