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).
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.
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 (.)
tar was extracted. If you look into the files you'll see the old contents. So --overwrite is default.
gz using option -xvzf : This command extracts files from tar archived file.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With