How do I prevent tar from overwriting an existing archive?

人走茶凉 提交于 2019-12-01 09:19:39

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!