温馨提示×

nohup日志如何重定向

小樊
42
2026-07-10 01:15:49
栏目: 编程语言

在 Linux 中,nohup 默认会把输出写到当前目录下的 nohup.out 文件。如果你想自定义日志重定向,常见用法如下:


1️⃣ 基本用法(重定向 stdout 和 stderr)

nohup command > app.log 2>&1 &

含义:

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

最常用


2️⃣ 只重定向标准输出

nohup command > app.log &

⚠️ 此时 stderr 仍会输出到 nohup.out


3️⃣ 只重定向标准错误

nohup command 2> error.log &

4️⃣ 分别重定向 stdout 和 stderr

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

5️⃣ 追加日志(而不是覆盖)

nohup command >> app.log 2>&1 &
  • >>:追加写入
  • 适合长期运行程序

6️⃣ 丢弃日志(不记录)

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

7️⃣ 指定工作目录(常见场景)

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

8️⃣ 查看后台任务

jobs

ps -ef | grep command

9️⃣ 示例(Java 程序)

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

✅ 推荐写法(生产环境)

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

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

  • 使用的 命令
  • 是否 长期运行
  • 是否需要 按日期切分日志

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

0