温馨提示×

centos nohup日志如何重定向

小樊
47
2026-07-20 20:49:15
栏目: 智能运维

CentOS(以及大多数 Linux) 中,nohup 默认会把日志输出到当前目录下的 nohup.out,但你可以通过 重定向 自定义日志位置。


一、基本用法(重定向 stdout 和 stderr)

nohup command > app.log 2>&1 &

含义:

  • > app.log:标准输出重定向到 app.log
  • 2>&1:标准错误也重定向到标准输出(即同一个文件)
  • &:后台运行

最常用方式


二、分别重定向 stdout 和 stderr

nohup command > stdout.log 2> stderr.log &
  • stdout.log:正常输出
  • stderr.log:错误输出

三、追加日志(不覆盖)

nohup command >> app.log 2>&1 &

使用 >> 而不是 >,避免覆盖旧日志


四、指定工作目录 + 日志路径

nohup /opt/app/start.sh > /var/log/app.log 2>&1 &

✅ 推荐生产环境使用绝对路径


五、不生成 nohup.out 的方法

nohup command > /dev/null 2>&1 &

或只保留错误日志:

nohup command > /dev/null 2> error.log &

六、查看后台任务

jobs        # 当前 shell
ps -ef | grep command

七、常见错误示例

❌ 错误:

nohup command & > app.log

✅ 正确:

nohup command > app.log 2>&1 &

八、推荐生产标准写法

nohup java -jar app.jar > /var/log/app/app.log 2>&1 &

如果你愿意,可以告诉我:

  • 你是 Java / Python / Shell 程序
  • 是否有 按天切分日志 的需求

我可以给你更合适的方案(如 logrotatecronolog)。

0