سؤال

I backup files a few times a day on Ubuntu/Linux with the command tar -cpvzf ~/Backup/backup_file_name.tar.gz directory_to_backup/. I want to create a script that will create the file name automatically - check:

~/Backup/backup_file_name_`date +"%Y-%m-%d"`_a.tar.gz

if it exists, if it exists then replace "_a" with "_b" and then checks all the letters up to z. Create the first backup file that doesn't exist. If all the files up to z exist then add "_1" to the file name (with "_z") and check all the numbers until the file doesn't exist. Never change an existing file but only create new backup files. Do you know how to create such a script?

هل كانت مفيدة؟

المحلول 2

OK, I found a solution. I created the file ~/scripts/backup.sh:

#!/bin/bash

working_dir=`pwd`
backupname=""

if [ -z "$backupname" ]; then
    for l in {a..z} ; do
    if [ ! -f ~/Backup/backup_file_name_`date +"%Y-%m-%d"`_${l}.tar.gz ]; then
        backupname=~/Backup/backup_file_name_`date +"%Y-%m-%d"`_${l}.tar.gz
        break
    fi
    done
fi

if [ -z "$backupname" ]; then
    l="z"
    for (( i = 1 ; i <= 1000; i++ )) do
    if [ ! -f ~/Backup/backup_file_name_`date +"%Y-%m-%d"`_${l}_${i}.tar.gz ]; then
        backupname=~/Backup/backup_file_name_`date +"%Y-%m-%d"`_${l}_${i}.tar.gz
        break
    fi
    done
fi

if [ ! -z "$backupname" ]; then
    cd ~/projects/
    ~/scripts/tar.sh $backupname directory_to_backup/
    cd $working_dir
else
    echo "Oops! can't create backup file name."
fi

exit

The file ~/scripts/tar.sh contains this script:

#!/bin/bash

if [ -f $1 ]; then
    echo "Oops! backup file was already here."
    exit
fi
tar -cpvzf $1 $2 $3 $4 $5

Now I just have to type ~/scripts/backup.sh and the script backs up my files.

نصائح أخرى

You can do something like

for l in {a..z} ; do
    [[ -f ~/Backup/backup_file_name_`date +"%Y-%m-%d"`_${l}.tar.gz ]] && continue
    export backupname=-f ~/Backup/backup_file_name_`date +"%Y-%m-%d"`_${l}.tar.gz && break
done

# test if $backupname is properly set, what if `z` is used? I'm leaving this to you
# then backup as usual

tar -cpvzf $backupname directory_to_backup/

This iterates over the letters and if the required file exists skips setting the backupname variable.

Create a script which saves file with date like,

~/Backup/backup_file_name_${date}.tar.gz

and run that script a cron job if you want to take backup after some specific interval or run it manually if you dont have such requirement.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top