温馨提示×

CentOS中nohup命令的正确用法

小樊
41
2025-10-19 22:18:57
栏目: 智能运维

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

  1. 基本语法:
nohup command [arguments] &

其中,command 是要执行的命令,arguments 是传递给命令的参数,& 表示将命令放入后台运行。

  1. 将输出重定向到文件: 默认情况下,nohup 命令会将程序的输出发送到名为 nohup.out 的文件中。如果要将输出重定向到其他文件,可以使用以下语法:
nohup command [arguments] > output_file &

例如,将程序的输出重定向到名为 output.log 的文件:

nohup ./my_script.sh > output.log &
  1. 将错误输出重定向到文件: 如果要将错误输出重定向到其他文件,可以使用以下语法:
nohup command [arguments] > output_file 2> error_file &

例如,将标准输出重定向到 output.log 文件,将错误输出重定向到 error.log 文件:

nohup ./my_script.sh > output.log 2> error.log &
  1. 同时将标准输出和错误输出重定向到同一个文件:
nohup command [arguments] > output_file 2>&1 &

例如,将标准输出和错误输出都重定向到 output.log 文件:

nohup ./my_script.sh > output.log 2>&1 &
  1. 使用 nohup 命令运行守护进程: 在 CentOS 系统中,可以使用 nohup 命令运行守护进程,例如启动 Apache 服务:
nohup systemctl start httpd &

总之,nohup 命令在 CentOS 系统中的正确用法是将命令放入后台运行,并将输出重定向到文件,以便在关闭终端或断开连接后程序仍能继续运行。

0