nohup
命令用于在后台运行程序,即使关闭终端或断开连接,程序也会继续运行
以下是如何将 nohup
命令与 cron
作业结合使用的步骤:
打开终端。
输入 crontab -e
命令以编辑当前用户的 cron
作业表。如果这是您第一次使用 crontab
,系统可能会提示您选择一个文本编辑器。
在打开的 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)
例如,如果您希望每天凌晨 1 点运行名为 my_script.sh
的脚本,您可以添加以下行:
0 1 * * * nohup /path/to/your/script/my_script.sh > /path/to/output.log 2>&1 &
这里,nohup
命令用于在后台运行 my_script.sh
脚本。>
符号将标准输出重定向到 output.log
文件,2>&1
将标准错误重定向到标准输出,&
符号将命令放入后台运行。
cron
作业表。现在,您的 cron
作业已经设置好了,将在指定的时间运行 my_script.sh
脚本,并将输出重定向到 output.log
文件。注意:确保您的脚本具有可执行权限。您可以使用 chmod +x /path/to/your/script/my_script.sh
命令为脚本添加可执行权限。