Monday, February 26, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 534  / 1 Year ago, tue, september 27, 2022, 3:29:54

How can I rename a log or error file to prevent overwriting?
I have a bash script that produces an output log file.
When re-running the script I want the old log files to be preserved by changing the name of the every logfile depending on the name of the last file created.
For example:


1st run: script.sh > log.file produces log.file1
2nd run: script.sh > log.file produces log.file2
3rd run: script.sh > log.file produces log.file3
Basically every run needs to check the last log file and count one up.


More From » bash

 Answers
6

Here is an example on how to do it using a loop in bash:


i=1
filename="log.file"
while [ -f $filename$i ]
do
i=$((i + 1))
done
filename=$filename$i
script.sh > $filename

We will have i=1 and it will increment each time until a file named log.file$i is created. This way each time a new file is created the last value of i is appended to $filename and then used as the output file for the script.


[#17] Tuesday, September 27, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ousear

Total Points: 395
Total Questions: 114
Total Answers: 89

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
ousear questions
Thu, Nov 25, 21, 00:51, 2 Years ago
Tue, Feb 22, 22, 17:47, 2 Years ago
Wed, Jul 6, 22, 14:55, 2 Years ago
;