I’ve been getting into server stuff lately. Having a NAS is great, especially when you can access it via the internet (I use WireGuard to access my home network.) No more flash drives!
One thing I did lately was create a script to backup the contents of each of my computers to a backup share on the NAS. Since I tend to copy a lot of files from the NAS to my local computers though I wanted a script that would be a bit more selective, that way I’m not copying tons of files that already exist elsewhere on the NAS. For those files I don’t want to backup I generally keep them in a directory called ~/not-backed-up/
To do that I just have to edit the script for each computer it’s on, just the destination
and dirs
variables at the top.
Then just make it an executable script:
$ chmod +x backup-laptop.sh
and run it:
$ ./backup-laptop.sh
#~/bin/bash # MAKE SURE TO USE ABSOLUTE PATHS!! # this is the backup destination, set it to whatever is needed destination="/Volumes/BackupServer/macbook-m3" # enter full paths of files/folders to backup. make sure # to omit the slash at the end so the folder itself # will be copied too instead of just the contents in it dirs=( "/Users/me/Documents" "/Users/me/Desktop" "/Users/me/Pictures" "/Users/me/Movies" "/Users/me/Downloads" "/Users/me/DataGripProjects" "/Users/me/Documents" "/Users/me/programming" "/Users/me/.gitconfig" "/Users/me/.vimrc" "/etc/hosts" ) function print_message() { # need to add or remove the -e flag depending on Mac OS or not local msg=$1 if [[ "$OSTYPE" == "darwin"* ]]; then echo "$msg" else echo -e "\t$msg" fi } # check if the user said to auto-continue by passing the "-y" argument confirm=false if [[ "$1" == "-y" ]]; then confirm=true fi # tell user what we're backing up and to where print_message "rsync destination:" print_message "$destination" print_message "local directories being backed up: " for src in "${dirs[@]}"; do print_message "\t$src" done # if the user didn't pass the -y flag then we ask if they want to continue if [[ "$confirm" == false ]]; then print_message "\r\nPlease note the source directories cannot end in / if any do, fix the script and re-run. " # prompt the user to continue (if needed) while true; do read -p "Continue backup? (y/n): " response case "$response" in [Yy]*) # just checks first letter is y for yes print_message "Continuing..." break; ;; [Nn]*) # first letter is n for no print_message "Exiting." exit 1 ;; *) print_message "Invalid response. Please answer yes or no." # loop back to top of while and ask again ;; esac done else print_message "\r\nDetected '-y' flag, skipping confirmation" fi # echo "Running rsync command..." print_message "Running rsync command..." # do the actual backup rsync -rh --update --delete --stats --info=progress2 "${dirs[@]}" "$destination" print_message "\r\nFinished backup."