Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent tar from overwriting an existing archive?

Tags:

linux

shell

tar

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/, (the file name contains the date in YYYY-MM-DD format and a letter from a to z - a is the first backup for this date etc.) but I want to create a new archive, not overwrite the archive if it already exists. How do I prevent tar from overwriting an existing archive? If the archive exists, I want tar to exit without doing anything (and if possible, display an error message).

like image 345
Uri Avatar asked Feb 10 '14 15:02

Uri


People also ask

Will tar overwrite existing archive?

Changing How tar Writes Files. Normally, tar writes extracted files into the file system without regard to the files already on the system--files with the same name as archive members are overwritten.

Does tar keep original file?

The tar command will never move or delete any of the original directories and files you feed it – it only makes archived copies. You should also note that using a dot (.)

Does tar overwrite by default?

tar was extracted. If you look into the files you'll see the old contents. So --overwrite is default.

What does the command tar XVZF * .tar do?

gz using option -xvzf : This command extracts files from tar archived file.


1 Answers

Check the existence of the file beforehand:

if [ -f ~"/Backup/[backup_file_name].tar.gz" ]; then
    echo "ooops backup file was already here"
    exit
fi
tar -cpvzf ~/Backup/[backup_file_name].tar.gz directory_to_backup/

Note that the ~ has to be outside the double quotes if you want it to be expanded.


Update

Thanks. Do you know how to make the archive file name and directory to backup as command line arguments? The file name includes the full path.

You can use $1, $2 and so on to indicate the parameters. For instance:

if [ -f $1 ]; then
    echo "ooops backup file was already here"
    exit
fi
tar -cpvzf $1 $2

And then call the script with:

./script.sh file backup_dir
like image 120
fedorqui 'SO stop harming' Avatar answered Oct 14 '22 03:10

fedorqui 'SO stop harming'