Skip to content
Advertisement

bash script to kill a python script after starting another same python script

I start a python script and then after some time i want to kill it. but before killing it I want to start another copy of this same script and then kill the previous one after starting new one. I want to do this in loop.

here is my code , i just need a clean way to kill scripts.I do not want to use timeouts.

#!/bin/bash 
while true
do
    echo "starting FIRST Consumer.py : $(date +"%T")"
    python3 /home/irum/Desktop/Marketsyc/Consumer.py &

    sleep 20
    echo "starting SECOND Consumer.py : $(date +"%T")"
    python3 /home/irum/Desktop/Marketsyc/Consumer.py &
    # Here I want to kill FIRST Consumer.py
    sleep 20
    # Here I want to kill SECOND Consumer.py

done

Advertisement

Answer

You can get the PID of the first process to kill it afterwards:

#!/bin/bash 

while true
do
    echo "starting FIRST Consumer.py : $(date +"%T")"
    python3 /home/irum/Desktop/Marketsyc/Consumer.py &
    pid=$!
    sleep 20

    echo "starting SECOND Consumer.py : $(date +"%T")"
    python3 /home/irum/Desktop/Marketsyc/Consumer.py &
    new_pid=$!

    # Here I want to kill FIRST Consumer.py
    kill "$pid"
    sleep 20

    # Here I want to kill SECOND Consumer.py
    kill "$new_pid"
done
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement