Bash script for backups
Example of bash scripts to automate files and folders backups
Published in
2 min readSep 24, 2023
Objective : create a script to automate backing up files and folders to a Git account, while securing them with AES encryption.
For anyone who doesn’t trust/want a Cloud to manage their stuff.
Menu
Bash script model: a “menu” script calling dedicated sub-scripts according to user’s choices. Create as many scripts as you’ll have backup scenarii.
#!/bin/bash
cd /home/user/working-directory
# loop menu
while true; do
# Display options
echo "BACKUP TOOL"
echo "................."
echo "1 Backup 1"
echo "2 Backup 2"
echo "3 Backup 3"
echo "................."
# Read user input
read -n 1 -p "Enter your choice (#) or exit (x): " choice
echo
# Perform the selected action based on user input
case "$choice" in
1)
echo "Backup 1"
./script_1 ;;
2)
echo "Backup 2"
./script_2 ;;
3)
echo "Backup 3"
./script_3 ;;
x)
exit 0 ;;
*)
echo "Invalid choice..." ;;
esac
done
All sub-scripts must be in the parent working directory.
Sub script model
This script will :
- copy the file(s) or folder to backup in your Git directory (to be created first of course)
- encrypt it using GPG AES256 : you’ll be prompted for a passphrase
- clean the directory
- push the encrypted file to Git
#!/bin/bash
# WD
cd /home/user/git-directory
# copy file to backup
cp /home/user/other-directory/file.ext ./file.ext
# encrypt file using GPG AES256
gpg -c file.kdbx
# rename with date
now=$(date +%Y%m%d_%H%M)
mv file.kdbx.gpg ./"keep_$now.gpg"
read -p ">> Continue to GIT ? " -n1 -s
# Remove temp files
rm ./file.ext
# GIT operations
git pull
git add *.gpg
git commit -a -m "File backup"
git push
To decrypt your file (you’ll be prompted for the passphrase):
gpg -d --output restored_file.ext ./*gpg
Enjoy!