#!/bin/bash
#source_dir=(# 你的备份目录,一行一个,例如 /opt/container/server1
/opt/container/server2
)date_format=$(TZ="UTC" date +%Y%m%d)# 备份文件的存放位置(可选)backup_base_dir="$HOME/backup/application"force_repack=0# Default: do not force repack# Define backup functions# 函数名为你的rclone配置的远程存储名,仿照下面的添加即可b2(){remote_dir="rclone远程存储名:远程备份路径" backup_to_remote "$remote_dir""$1"}# Generic backup functionbackup_to_remote(){localremote_dir="$1"localsource_full_path="$2"localsource_name=$(basename "$source_full_path")# check output directorytarget_dir="$backup_base_dir/$source_name"if[ ! -d "$target_dir"];thenecho"$target_dir directory not exists, creating..." mkdir -p "$target_dir"fi# archive directorytarget_full_path="$target_dir/${source_name}_backup_${date_format}.tar.gz"if[ ! -f "$target_full_path"]||["$force_repack" -eq 1];thenif["$force_repack" -eq 1];thenecho"Force repack is enabled. Recreating archive: $target_full_path"elseecho"Creating archive: $target_full_path"fi tar -zcf "$target_full_path""$source_full_path"fi# backup archive fileecho"Starting backup to $remote_dir: ${target_full_path}" rclone copy "$target_full_path""$remote_dir/${source_name}" -P
echo""}# Process each source directoryprocess_directory(){localdir="$1"localbackup_targets=("${@:2}")# Get all arguments after the directoryif[ -z "$backup_targets"];thenecho"No backup targets specified for $dir. Skipping."returnfifor target in "${backup_targets[@]}";doiftype"$target" > /dev/null 2>&1;thenecho"Backing up $dir to $target""$target""$dir"# Call the backup function with the directoryelseecho"Error: Backup target '$target' not found."fidone}# Main script logic# Parse command line argumentswhilegetopts"f" opt;docase$opt in
f)force_repack=1;;\?)echo"Invalid option: -$OPTARG" >&2exit1;; :)echo"Option -$OPTARG requires an argument." >&2exit1;;esacdoneshift$((OPTIND -1))# Shift off the options, leaving only backup targetsif[$# -eq 0];thenecho"Usage: $0 [-f] <backup_target> [backup_target2 ...] "echo" -f: Force re-packaging the local archive file."echo"Available backup targets: b2"exit1fi# Loop through each source directory and apply the specified backupsfor source_dir_item in "${source_dir[@]}";do process_directory "$source_dir_item""$@"doneecho"Backup process completed."