Linux Automation Tip: Kill Script if Already Running

in #linux6 years ago (edited)

kill a running script bash

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

  1. 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.
  2. Grep looks the text output by the PS for the keyword supplied on the command-line ($1).
  3. Awk takes the columns of text from the Grep search and extracts the second column, which is our process IDs.
  4. 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.
  5. 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.

 


Posted from my blog with SteemPress : https://makerhacks.com/linux-automation-tip-kill-script-already-running/

Sort:  

I use "killall" but sometimes you don't have it, and your little script will be useful.

Yeah I looked at killall but you seemed to need to know the precise command whereas using Grep can find anything containing the string - I might be wrong of course!

No, you are right. This is the default behaviour but there is a flag where you can put a regex too.

Coin Marketplace

STEEM 0.29
TRX 0.12
JST 0.034
BTC 63748.21
ETH 3314.18
USDT 1.00
SBD 3.90