从 bash 函数调用时忽略 tar 排除文件夹

从 bash 函数调用时忽略 tar 排除文件夹

以下代码不起作用,排除文件夹被 tar 忽略。我该如何解决这个问题?请注意,我可能有多个排除文件夹和多个要备份的文件夹。

date=`date +%Y%m%d`

# tar_create function
# ARG1=<filename_to_write> ARG2=<exclusions> ARG3=<folders>
tar_create () {
    exclude_options=()
    if [ ${#exclude[@]} -ne 0 ]; then
        for x in "${2[@]}"; do
            exclude_options+=(--exclude="$x")
        done
    fi
    echo "$(date '+%Y%m%d:%H:%M:%S'): Running tar czvpf "${1}" "${exclude_options[@]}" ${@:3}"
    tar czvpf "${1}" "${exclude_options[@]}" ${@:3} 2>&1 > "${1}.txt"
    ret=$?
    if [ $ret != 0 ] && [ $ret != 1 ]; then
        echo "$(date '+%Y%m%d:%H:%M:%S'): Error: tar returned $ret for ${1}"
        echo "$(date '+%Y%m%d:%H:%M:%S'): Error: tar returned $ret for ${1}" >> "${1}-errors.txt"
    fi
    echo "$(date '+%Y%m%d:%H:%M:%S'): End tar czvpf "${1}" "${exclude_options[@]}" ${@:3} : return $ret"
}

# do_backup function
# ARG1=<filename_to_write> ARG2=<root folder to backup> ARG3=<exclusions in tar format> ARG4=<folders to backup>
do_backup () {
    if [ ! -d "$(dirname "${1}")" ] || [ ! -w "$(dirname "${1}")" ]; then
        echo "Folder ${1} doesn't exist or isn't writable, can't write backup files" >> backup-error.log
    fi
    if [ ! -d "$(dirname "${2}")" ]; then
        echo "Folder to backup ${1} doesn't exist" >> backup-error.log
    fi

    declare -a exclude=("${!3}")
    declare -a folders=("${!4}")
    declare -a all=("${exclude[@]}" "${folders[@]}")

    echo "cd ${2}"
    cd "${2}"
    echo "tar_create ${1} ${3} ${4}"
    tar_create "${1}" "${3}" "${4}"
}
exclude=( './photos' './videos' './archives' )
folders=( './' )
do_backup "/hdd/backup-$date.tar.gz" "/home/datastorez" "${exclude[@]}" "${folders[@]}"

答案1

这是如何使用函数创建 tar 文件的最小示例。在您的代码中,当作为参数传递给函数时,无法区分排除项和备份文件夹。使用语法将数组扩展为多个单词"${name[@]}"

示例:如果exclude数组为空,则参数$3indo_backup将是 的第一个元素folders。如果数组中有两个项目exclude,则 的第一个元素folders将为$5

变化:

  • $1: 备份的名称
  • $2: 切换到的目录
  • $3:数组变量的名称excludes。在函数中,我们使用nameref属性 ( -n) 声明一个变量来访问数组元素。
  • $4- $n:要备份的目录
# ARG1=<filename_to_write> ARG2=<change_to_dir> ARG3=<name_of_exclude_array> ARG4...=<directories>
tar_create () {
    local -n excl=$3
    local exclude_options=()
    for i in "${excl[@]}"; do
        exclude_options+=( --exclude "$i" )
    done

    tar czvpf "$1" -C "$2" "${exclude_options[@]}" "${@:4}"
}

exclude=( ./photos ./videos ./archives )
dirs=( ./ )
tar_create /hdd/backup-$(date +%Y%m%d).tar.gz /home/datastorez exclude "${dirs[@]}"

相关内容