直接上源码
#!/bin/bash
filename=$1
if [ -e $filename ] ; then
yesterday=`date -d yesterday +%Y%m%d`
cp $filename $filename.$yesterday
now=`date '+%Y-%m-%d%H:%M:%S'`
echo "========split log at $now========" > $filename
echo "========split log $filename to $filename.$yesterday at $now========"
else
echo "$filename not exist."
fi
脚本中运行这行代码echo "========split log at $now========" > $filename后,$filename中确实被重写,但是重写之后的文件中多了N多字节的\0,大概有十几K字节。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
经过沟通,题主的问题出在重定向文件的打开方式上面。
如果使用
>进行重定向,nohup会以w+方式打开文件,这种方式写文件会记录文件当前偏移量,外部脚本 truncatelog.file后nohup还会继续往当前记录的文件偏移量写内容,导致前面很大一段被跳过,跳过部分被自动填充\0。如果想要 truncate 正常工作,命令应该使用
>>进行重定向,也就是以a方式打开并写入文件,这样就没有任何问题了。