nohup
命令用于在后台运行程序,即使关闭终端或断开连接,程序也会继续运行
以下是如何将 nohup
命令与 cron
作业结合的步骤:
打开终端。
输入 crontab -e
命令来编辑当前用户的 cron
作业表。
在打开的编辑器中,添加一行新的 cron
作业。cron
作业的格式如下:
* * * * * command-to-be-executed
- - - - -
| | | | |
| | | | ----- Day of the week (0 - 7) (Sunday to Saturday; 7 is also Sunday)
| | | ------- Month (1 - 12)
| | --------- Day of the month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
command-to-be-executed
部分,使用 nohup
命令以及要执行的命令。例如,如果您希望在每天凌晨 1 点运行名为 my_script.sh
的脚本,您可以这样写:0 1 * * * nohup /path/to/my_script.sh > /path/to/output.log 2>&1 &
这里,> /path/to/output.log
将标准输出重定向到指定的日志文件,2>&1
将标准错误重定向到标准输出(即日志文件),&
将命令放入后台运行。
cron
作业已经设置好了,将在指定的时间运行 nohup
命令。注意:请确保您的脚本具有可执行权限。您可以使用 chmod +x /path/to/my_script.sh
命令为脚本添加可执行权限。