nohup(no hang-up)命令在 Linux 中用于在后台运行程序,即使关闭终端或断开连接,程序也会继续运行
使用 nohup 命令启动程序:
nohup your_command &
这将在后台运行 your_command,并将输出重定向到名为 nohup.out 的文件。
创建一个 shell 脚本,例如 run_my_command.sh,并在其中添加以下内容:
#!/bin/bash
while true; do
nohup your_command > /dev/null 2>&1 &
wait $!
echo "Restarting your_command in 5 seconds..."
sleep 5
done
这个脚本将无限循环地运行 your_command,并在每次执行完成后等待 5 秒钟。> /dev/null 2>&1 将输出重定向到 /dev/null,这样你就不会看到任何输出。
为脚本添加可执行权限:
chmod +x run_my_command.sh
使用 nohup 命令运行脚本:
nohup ./run_my_command.sh &
这将在后台运行 run_my_command.sh,即使关闭终端或断开连接,程序也会继续运行并自动重启 your_command。
请注意,这种方法仅适用于简单的用例。对于更复杂的任务管理和监控,你可能需要考虑使用进程管理器(如 systemd、supervisord 或 pm2)。