nohup
命令本身不提供直接限制輸出文件大小的功能。但是,你可以使用 logrotate
工具或編寫一個簡單的腳本來實現這個需求。
方法一:使用 logrotate
myapp.conf
的 logrotate 配置文件:/path/to/your/output.log {
size 100M
rotate 5
compress
missingok
notifempty
create 640 user group
}
這個配置表示,當地文件大小達到 100M 時,logrotate 會自動壓縮并創建一個新的日志文件。保留 5 個壓縮日志文件。
crontab
每分鐘運行一次 logrotate:* * * * * /usr/sbin/logrotate /path/to/your/myapp.conf
方法二:編寫一個簡單的腳本
創建一個名為 myapp.sh
的腳本:
#!/bin/bash
output_file="/path/to/your/output.log"
max_size=100M
if [ -f "$output_file" ]; then
file_size=$(stat -c%s "$output_file")
if [ $file_size -gt $(numfmt --from=iec $max_size) ]; then
mv "$output_file" "${output_file}.$(date +%Y%m%d%H%M%S)"
fi
fi
nohup your_command_here >> "$output_file" 2>&1 &
這個腳本會檢查輸出文件的大小,如果超過 100M,它會將文件重命名并添加一個時間戳。然后,它會運行 nohup
命令并將輸出追加到新的文件中。
chmod +x myapp.sh
./myapp.sh
這樣,你的輸出文件大小將被限制在 100M 以內。