问题
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).
回答1:
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
回答2:
I created the file ~/scripts/tar.sh
:
#!/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/tar.sh ~/Backup/backup_file_name_`date +"%Y-%m-%d"`_a.tar.gz directory_to_backup/
And the backup file is created if the file doesn't exist.
来源:https://stackoverflow.com/questions/21680601/how-do-i-prevent-tar-from-overwriting-an-existing-archive