清空 nohup.out 日志文件有几种安全且常用的方法,取决于你的需求(是否要保留进程继续写日志)。
truncate 或 : > 清空(不中断进程)这是在 不停止程序 的情况下清空日志的最佳方式。
: > nohup.out
或:
truncate -s 0 nohup.out
✅ 优点:
cat /dev/nullcat /dev/null > nohup.out
等价于上面的方法,也非常常见。
rm nohup.out
⚠️ 风险:
nohup.outnohup xxx > log.out 2>&1 & 启动的清空方式一样:
: > log.out
/dev/nullnohup your_command > /dev/null 2>&1 &
logrotate(生产环境推荐)示例 /etc/logrotate.d/myapp:
/path/to/nohup.out {
size 100M
rotate 5
copytruncate
missingok
notifempty
}
✅ copytruncate 可以不重启进程完成日志轮转
lsof -p <PID> | grep nohup
| 场景 | 命令 |
|---|---|
| 清空日志但不停进程 | : > nohup.out ✅ |
| 生产环境 | logrotate + copytruncate ✅ |
| 不想产生日志 | > /dev/null 2>&1 ✅ |
如果你愿意,可以把你的 启动命令 或 **系统环境(Linux / macOS)**发给我,我可以帮你给出最合适的方案。