1#!/usr/bin/env bash
2# shellcheck disable=SC2155
3
4# ------------------------------------------------------------
5# Configuration: Add files and directories to backup below
6# ------------------------------------------------------------
7PATHS_TO_BACKUP=(
8 # provide absolute paths to files and directories
9 # ~ does not work here, use $HOME instead
10
11 "$HOME/.config"
12 # "/etc"
13 # "/path/to/important/file.txt"
14 # "/path/to/important/directory"
15 # Add as many paths as you need
16)
17
18# use rsync if available, otherwise fall back to cp
19cp() {
20 if command -v rsync &> /dev/null; then
21 command rsync -a "$@"
22 else
23 command cp -r "$@"
24 fi
25}
26
27backup_item() {
28 local path="$1"
29 local backup_dir="$2"
30 local timestamp="$(date +"%Y%m%d_%H%M%S")"
31
32 # Check if the path exists
33 if [ ! -e "$path" ]; then
34 echo "đ Error: $path does not exist"
35 return 1
36 fi
37
38 # Get basename of the path
39 local basename="$(basename "$path")"
40
41 # Create backup name with timestamp
42 if [ -n "$backup_dir" ]; then
43 # If backup directory specified, put backup there
44 local backup_name="${backup_dir}/${basename}.${timestamp}.bak"
45
46 # Ensure backup directory exists
47 mkdir -p "$backup_dir"
48 else
49 # Otherwise put backup in same directory as original with .bak extension
50 local backup_name="${path}.${timestamp}.bak"
51 fi
52
53 # Make the backup
54 if [ -d "$path" ]; then
55 # It's a directory
56 cp "$path" "$backup_name"
57 echo "â
Directory backup created: $backup_name"
58 else
59 # It's a file
60 cp "$path" "$backup_name"
61 echo "â
File backup created: $backup_name"
62 fi
63}
64
65# Optional backup directory from command line argument
66BACKUP_DIR=""
67if [ $# -eq 1 ]; then
68 BACKUP_DIR="$1"
69 echo "âšī¸ Backup destination directory: $BACKUP_DIR"
70fi
71
72# Check if any paths are configured
73if [ ${#PATHS_TO_BACKUP[@]} -eq 0 ]; then
74 echo "đ Error: No paths configured for backup"
75 echo "đ Please edit the script and add paths to the PATHS_TO_BACKUP array"
76 exit 1
77fi
78
79echo "âšī¸ Starting backup at $(date)"
80
81# Process each configured path
82for item in "${PATHS_TO_BACKUP[@]}"; do
83 backup_item "$item" "$BACKUP_DIR"
84done
85
86echo "âšī¸ Backup complete! $(date)"