Can you please comment on the script below? It backs up my local password database to a remote repository if a change is detected. It works as intended. I'd like some comments in terms of syntax, security, portability, readability, etc.
#!/bin/bash
# Compares local and remote copies of the keepass db. If there are any diff, the local replaces remote, as local is the
# master.
# KeepassXC tends to make some meta-data changes (DB preferences, last opened group...)
# which will be picked up by this script. Therefore, a sync might happen even if no entry has been
# added/modified/deleted
#
# This script is run periodically by cron (crontab -l to view the schedule). Below shows it runs Mondays at 10am
# 0 10 * * * /home/notfound/bin/backupKeepassdb.sh
# It requires:
# - bash as shell (bash initialises $HOSTANME)
# - ts from moreutils package for timestamps in the logs
#
# It should be placed in the bin directory of the user so that it automatically appears in $PATH
#
# Usage:
# backupKeepassDB.sh
log () {
echo $1 | ts '[%F %H:%M:%.S]' >> /home/notfound/Logs/backupkeepassdb.log
}
log_and_mail () {
log "$2"
echo "$2" | mailx -s "$HOSTNAME - $(basename "$0") - $1" $notification_recipient
}
log_and_mail_and_exit () {
log_and_mail "$1" "$2"
exit
}
clone_remote_repo_or_exit () {
cd $temp_dir
export GIT_SSH_COMMAND="SSH_AUTH_SOCK='/run/user/1000/keyring/ssh' ssh -i $repo_identity_file_path -o IdentitiesOnly=yes -F /dev/null"
git clone [email protected]:notfound/notfound.git &> /dev/null
if [ "$?" != 0 ]; then
log_and_mail_and_exit "$email_subject_failure" "Failed to clone remote repository"
fi
}
check_db_is_readable_or_exit () {
if [ ! -f "$1" ]; then
log_and_mail_and_exit "$email_subject_failure" "$1 not found or not readable"
fi
}
push_to_remote () {
rm -rf "$remote_keepassdb_path"
cp "$local_keepassdb_path" "$local_repository_path"
cd "$local_repository_path"
git add . &> /dev/null
git commit -m "Update from $HOSTNAME" &> /dev/null
git push origin main &> /dev/null
}
temp_dir=`mktemp -d`
local_keepassdb_path=/home/notfound/Documents/Secret/Passwords/KeepassXC/Passwords.kdbx
local_repository_path=$temp_dir/backup
remote_keepassdb_path=$local_repository_path/Passwords.kdbx
[email protected]
repo_identity_file_path=/home/notfound/.ssh/notfoundToGitlab_id_ed25519
email_subject_failure="Failed Password backup"
log "Starting Password db backup"
clone_remote_repo_or_exit
check_db_is_readable_or_exit "$local_keepassdb_path"
check_db_is_readable_or_exit "$remote_keepassdb_path"
remote_db_hash=($(sha256sum $remote_keepassdb_path))
local_db_hash=($(sha256sum $local_keepassdb_path))
if [ "$remote_db_hash" != "$local_db_hash" ]; then
(push_to_remote &&
log_and_mail "Successfully Updated Remote Keepass DB" "Local Keepass DB different from Remote. Remote has been updated.") ||
log_and_mail_and_exit "$email_subject_failure" "Failed to push remote repository"
else
log "Local Keepass DB and Remote Keepass DB are identical. No update needed"
fi