How to kill python script with bash script

You can use the ! to get the PID of the last command.

I would suggest something similar to the following, that also check if the process you want to run is already running:

#!/bin/bash

if [[ ! -e /tmp/test.py.pid ]]; then   # Check if the file already exists
    python test.py &                   #+and if so do not run another process.
    echo $! > /tmp/test.py.pid
else
    echo -n "ERROR: The process is already running with pid "
    cat /tmp/test.py.pid
    echo
fi

Then, when you want to kill it:

#!/bin/bash

if [[ -e /tmp/test.py.pid ]]; then   # If the file do not exists, then the
    kill `cat /tmp/test.py.pid`      #+the process is not running. Useless
    rm /tmp/test.py.pid              #+trying to kill it.
else
    echo "test.py is not running"
fi

Of course if the killing must take place some time after the command has been launched, you can put everything in the same script:

#!/bin/bash

python test.py &                    # This does not check if the command
echo $! > /tmp/test.py.pid          #+has already been executed. But,
                                    #+would have problems if more than 1
sleep(<number_of_seconds_to_wait>)  #+have been started since the pid file would.
                                    #+be overwritten.
if [[ -e /tmp/test.py.pid ]]; then
    kill `cat /tmp/test.py.pid`
else
    echo "test.py is not running"
fi

If you want to be able to run more command with the same name simultaneously and be able to kill them selectively, a small edit of the script is needed. Tell me, I will try to help you!

With something like this you are sure you are killing what you want to kill. Commands like pkill or grepping the ps aux can be risky.


Use pkill command as

pkill -f test.py

(or) a more fool-proof way using pgrep to search for the actual process-id

kill $(pgrep -f 'python test.py')

Or if more than one instance of the running program is identified and all of them needs to be killed, use killall(1) on Linux and BSD

killall test.py