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:


 case $1 in
       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;;
       kill 'cat /home/my_name/scripts/test.pid';;
       echo "usage: "$1" {start|stop}" ;;
 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:
    count += 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

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!

  • You can also try to use systemd service and call python directly in ExecStart instead of bash script.
    – mrc02_kr
    Commented Apr 9, 2021 at 10:53

1 Answer 1

  kill 'cat /home/my_name/scripts/test.pid';;

You probably want that to be:

  kill `cat /home/my_name/scripts/test.pid`;;

(backticks instead of single quotes)

  • That was quick and simple! Thank you very much!
    – Alasdair
    Commented Apr 9, 2021 at 0:15
  • 1
    It's easy to confuse normal quote characters with back quotes. To avoid this, use $(cat /home/my_name/scripts/test.pid) instead of back quotes. Commented Apr 9, 2021 at 0:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .