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 以内。