The following code didn't work, exclude folders are ignored by tar. How can I fix that ? Please note I may have multiple exclude folders and multiple folders to backup.
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[@]}"