Reputation: 61
I have a log file which i need to take a backup,
Then empty the file instead of deleting it,
Deleting the file will cause someother script to get triggered,
Hence i should only empty it.
Please suggest me a way?
Upvotes: 0
Views: 939
Reputation: 43
AFAIK there is no easy way to backup a file and empty it at the same time. I faced a similar problem and what I ended up doing is reading the original file line by line and copy them to a new file while keeping count of line numbers. Then I simply remove that number of lines from the original file. I use this to manually rotate some log files for which standard rotating approaches were not an option.
ORIGINAL_FILE="file.log"
NEW_FILE="$(date +%s).file.log"
unset n
while read line; do echo "$line" >> $NEW_FILE; : $((n++)); done < $ORIGINAL_FILE
if [[ -v n ]]; then
sed -i "1,$n d" $ORIGINAL_FILE
fi
Upvotes: 0
Reputation: 86
After you've read from the file you can just overwrite the file with > filename
This overwrites the file with nothing. It is also equivalent to cat /dev/null > filename
.
similar solutions referenced here
Upvotes: 3