I have a bash script that calls a Python script that I want running continuously in the background. I can start the bash script, and the Python script runs, but I can't stop it using the "stop" command with the bash script.
Here is the bash script:
#!/bin/bash case $1 in start) echo 'Running test.py' exec 2>&1 /opt/anaconda3/envs/my_env/bin/python /home/my_name/scripts/test.py & echo 'Assigning pid' echo $! > /home/my_name/scripts/test.pid;; stop) kill 'cat /home/my_name/scripts/test.pid';; *) echo "usage: "$1" {start|stop}" ;; esac exit 0
And here is the Python script:
import time from pathlib import Path count = 0 while True: with open(Path(__file__).parent.resolve() / "test.txt", 'a') as f: f.write(str(count)) count += 1 time.sleep(1)
The Python code works fine so it's not worth discussing much. It just writes an integer to a text file every second, each time incrementing by one.
Here is what I get on the command line from within the folder containing the Python and bash scripts:
$ sudo ./test.sh start Running test.py Assigning pid $ sudo ./test.sh stop ./test.sh: line 10: kill: cat /home/my_name/scripts/test.pid: arguments must be process or job IDs $ ps -aux | grep test root 91366 0.1 0.0 26704 9320 pts/6 S 19:39 0:00 /opt/anaconda3/envs/my_env/bin/python /home/my_name/scripts/test.py VEIC\da+ 92004 0.0 0.0 14436 1012 pts/11 S+ 19:41 0:00 grep --color=auto test $ cat test.pid 91366
So you can see the pid written to the pid file test.pid
matches the one shown with the command ps -aux | grep test
. But when trying to use the stop
command with the bash script I'm told that the contents of the pid file aren't a process or job ID.
I'm eventually hoping to use this in conjunction with Monit, but need to get past this bash script difficulty before I do so. Any help would be greatly appreciated!