Restart python script automatically even when it crashes in Linux

aja*_*aja 3 python linux shell scripting

I have a python program that has to be running all the time. If for some reason it was stopped I want to restart it automatically. I thought of having a cron that will run every n number of seconds and check the program is running. My shell script is looks like this:

#!/usr/bin/env bash
CM_COMMAND=`ps aux| grep abc| grep def| grep sudo`
LEN_COMMAND=${#CM_COMMAND}
if[["$LEN_COMMAND" -le "5"]] 
then
    echo "start the python program"
fi
exit
Run Code Online (Sandbox Code Playgroud)

When I run this script I am getting the error: my_prog.sh: line 4: $'if[[118\r -le 5]]\r': command not found'

What is the alternative of doing this and what is the problem with my script?

fro*_*ell 5

也许这会更健壮?

1)在启动时保存进程的PID:

{your_python_command} & echo $! >>/{some_folder}/your_app.pid
Run Code Online (Sandbox Code Playgroud)

2) 如果找不到 PID,此脚本将检查并重新启动。

#!/usr/bin/env bash

PID=`cat /{some_folder}/your_app.pid`

if ! ps -p $PID > /dev/null
then
  rm /{some_folder}/your_app.pid
  {your_python_command} & echo $! >>/{some_folder}/your_app.pid
fi
Run Code Online (Sandbox Code Playgroud)

3)要将其添加到cronjob:

crontab -e
Run Code Online (Sandbox Code Playgroud)

选择您的文本编辑器并在文件末尾添加这一行:

*/1 * * * * /{your_path}/{your_script_name}
Run Code Online (Sandbox Code Playgroud)

退出并保存

(这将每分钟运行一次脚本,检查 crontab 手册以设置您的确切间隔)