温馨提示×

如何使用nohup命令在Linux中实现自动化运维

小樊
44
2025-08-04 21:35:44
栏目: 智能运维

nohup(no hang-up)命令是 Linux 系统中用于在后台运行程序的命令,即使关闭终端或断开连接,程序也会继续运行

  1. 在命令行中输入 nohup,后面跟上要执行的命令,然后在其后添加 & 符号。例如,如果你想在后台运行一个名为 my_script.sh 的脚本,可以使用以下命令:
nohup ./my_script.sh & 
  1. 默认情况下,nohup 会将输出重定向到名为 nohup.out 的文件。如果你想将输出重定向到其他文件,可以使用以下命令:
nohup ./my_script.sh > output.log & 
  1. 如果你想在后台运行的程序不产生任何输出,可以将输出重定向到 /dev/null
nohup ./my_script.sh > /dev/null 2>&1 & 
  1. 若要检查后台进程的输出,可以使用 tail 命令实时查看日志文件:
tail -f nohup.out 
  1. 若要在后台运行的程序中捕获错误输出,可以将错误输出重定向到不同的文件:
nohup ./my_script.sh > output.log 2> error.log & 
  1. 若要在后台运行的程序中同时捕获标准输出和错误输出,可以使用以下命令:
nohup ./my_script.sh > output_and_error.log 2>&1 & 
  1. 若要在后台运行的程序中限制输出文件的大小,可以使用 logrotate 工具。首先,创建一个名为 my_script.sh.conf 的配置文件,包含以下内容:
/path/to/output.log { size 10M rotate 5 compress missingok notifempty create 640 user group } 

然后,使用 logrotate 命令运行配置文件:

logrotate /path/to/my_script.sh.conf 

这样,当 output.log 文件达到 10MB 时,它将被压缩并创建一个新的日志文件。最多保留 5 个压缩日志文件。

通过以上方法,你可以使用 nohup 命令在 Linux 中实现自动化运维。

0