温馨提示×

怎样用nohup记录日志

小樊
44
2026-09-03 10:30:53
栏目: 编程语言

在 Linux/Unix 系统中,nohup 常用来让进程在用户退出后继续运行,同时通常会把输出记录到日志文件。下面按常见用法说明。


一、基本用法(最常用)

nohup your_command > output.log 2>&1 &

说明:

  • nohup:忽略挂断信号
  • your_command:你要运行的命令
  • > output.log:标准输出写入 output.log
  • 2>&1:标准错误也写入同一个日志
  • &:后台运行

示例:

nohup python app.py > app.log 2>&1 &

二、分别记录 stdout 和 stderr

nohup your_command > out.log 2> err.log &
  • out.log:正常日志
  • err.log:错误日志

三、追加日志(不覆盖)

nohup your_command >> output.log 2>&1 &

>> 表示追加,而不是覆盖原文件。


四、不记录日志(丢弃输出)

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

五、查看日志

tail -f output.log

实时查看日志:

tail -f output.log

查看最后 100 行:

tail -n 100 output.log

六、结合 date 生成带时间的日志名(进阶)

nohup your_command > log_$(date +%Y%m%d_%H%M%S).log 2>&1 &

七、查看后台进程

jobs
ps aux | grep your_command

如果你有具体场景(如 Python / Java / Shell 脚本 / Docker),我可以给你更合适的示例。

0