Bash脚本覆盖现有的.tar.gz文件

时间:2018-02-19 13:00:23

标签: bash

我编写了一个小的bash文件来备份存储库。如果存档文件不存在,则应该创建它。此后,找到的文件应附加到现有文件中。

由于某种原因,存档会不断创建/重写。这是我的下面的脚本。任何人都可以看到逻辑错误的来源吗?

#!/bin/bash


REPOSITORY_DIR=$PWD/../repository
STORAGE_DAYS=30

#https://stackoverflow.com/questions/48585148/reading-names-of-imediate-child-folders-into-an-array-and-iterating-over-it?noredirect=1#comment84167181_48585148
while IFS= read -rd '' file; 
    do fbname=$(basename "$file");

    # Find all persisted (.CSV) files that are older than $STORAGE_DAYS
    files_to_process=($(find $REPOSITORY_DIR/$fbname -type f -name '*.csv' -mtime +$STORAGE_DAYS))

    backup_datafile=$REPOSITORY_DIR/$fbname/$fbname.data.tar.gz
    #echo $backup_datafile

    # If the tar.gz file does not exist, we want to create it
    # else (i.e. file exists), we want to add files to it
    # Solution from: https://stackoverflow.com/questions/28185012/how-to-create-tar-for-files-older-than-7-days-using-linux-shell-scripting

    NUM_FILES_FOUND=${#files_to_process[@]}
    if [ $NUM_FILES_FOUND -gt 0 ]; then
        echo  "Found ${#files_to_process[@]} files to process ..."

        if [ ! -f backup_datafile ]; then
            # Creating a new tar.gz file, since file was not found
            echo "Creating new backup file: $backup_datafile"
            tar cvfz $backup_datafile "${files_to_process[@]}"
        else
            echo "Adding files to existing backup file: $backup_datafile"
            # https://unix.stackexchange.com/questions/13093/add-update-a-file-to-an-existing-tar-gz-archive
            gzip -dc $backup_datafile | tar -r "${files_to_process[@]}" | gzip >$backup_datafile.new
            mv $backup_datafile.new $backup_datafile        
        fi

        # remove processed files
        for filename in "${files_to_process[@]}"; do
            rm -f "$filename"
        done

    else
        echo "Skipping directory: $REPOSITORY_DIR/$fbname/. No files found"
    fi


done < <(find "$REPOSITORY_DIR" -maxdepth 1 -mindepth 1 -type d -print0) 

2 个答案:

答案 0 :(得分:1)

这是出错的地方:

if [ ! -f backup_datafile ]; then

我想应该是

if [ ! -f $backup_datafile ]; then
          ^

或者更好的是,把它放在引号中:

if [ ! -f "$backup_datafile" ]; then

答案 1 :(得分:0)

  

如果[! -f backup_datafile];然后

我想你可能会错过data那里