Syed
Syed

Reputation: 61

Log File Backup and empty the file instead of deleting in linux

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

Answers (3)

gcasanova
gcasanova

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

sophisticasean
sophisticasean

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

Leon
Leon

Reputation: 12481

To empty a file you can use truncate -s 0 filename

Upvotes: 0

Related Questions