Garam Choi
Garam Choi

Reputation: 149

How can I tar gz files with file name date range?

I want to make a tar.gz file which compresses multiple files, selected by exact date range which composes the name of the files. for example, file names are

system.2020-01-21.log
system.2020-01-22.log
system.2020-01-24.log
...

I want to set the exact date range for selecting files to be compressed. The output file will be

system.2020-01-20-2020-02-20.log.tar.gz

I tried this one below.

LAST_LOG_FILES=`find $LOG_HOME/system*.log -newerBt $LAST_LOG_Y_M_D ! -newerBt $CURR_LOG_Y_M_D`
LOG_ZIP="$LOG_HOME/stage.$LAST_LOG_Y_M_D-$CURR_LOG_Y_M_D.log.tar.gz"
tar -czf $LOG_ZIP $LAST_LOG_FILES

However, this throws error below.

tar: Cowardly refusing to create an empty archive. Try `tar --help' or `tar --usage' for more information. 

I think this mean the command doesn't set file name range, resulting in empty archive.

If you know better command to do this operation, would you inform me? I appreciate it in advance.

Upvotes: 0

Views: 1500

Answers (1)

tshiono
tshiono

Reputation: 22032

If you want to select the log file to be compressed based on the filenames, you will need to compare the filenames one by one. Would you please try the following:

start="2020-01-20"
end="2020-02-20"
log_home="log"          # assign to your LOG_HOME

for f in "$log_home"/system.*.log; do
    base=${f##*/}       # strip leading directory name
    if [[ $base > system.$start.log && $base < system.$end.log || $base = system
.$start.log || $base = system.$end.log ]]; then
                        # if start <= base <= end
        files+=("$f")   # then add the file to the list to compress
    fi
done

if (( ${#files[@]} )); then
                        # if the list of the files is not empty
    log_zip="$log_home/system.$start-$end.log.tar.gz"
    tar -czf "$log_zip" "${files[@]}"
fi
  • The variable ${#files[@]} represents the number of elements in the array files. The condition test avoids the case the list is empty.
  • The expression "${files[@]}" expands the elements of the array as: "system.2020-01-21.log" "system.2020-01-22.log" ...

Upvotes: 2

Related Questions