Skip to content

Instantly share code, notes, and snippets.

@shimo164
Last active February 20, 2022 10:22
Show Gist options
  • Select an option

  • Save shimo164/d5cf3750bada0e82ac76e611eb3d3ea7 to your computer and use it in GitHub Desktop.

Select an option

Save shimo164/d5cf3750bada0e82ac76e611eb3d3ea7 to your computer and use it in GitHub Desktop.
Auto back up of any files to Github
#!/bin/bash
# Back up specific files on any directories.
# Using cron job, check update for each file.
# Up-to-date files are copied to local repository
# and pushed to github.
#
# Usage:
# $ bash ./cron_git_arbitray_file.sh
# cron example. execute at every 4am:
# 0 4 * * * (cd /home/dir/of/sh/ && bash cron_git_arbitrary_file.sh)
# Log: ./log/yyyymmdd.log is saved.
#
# Parameters
# ----------
# declare -a List=(
# "/home/user/full/path/to/file.file"
# "/home/user/.config/path/to/file.file"
# )
# REMOTE_REPO="github.com/username/reponame.git"
# LOCAL_REPO="/home/user/local/reponame/"
# SUBDIR_REPO="sub-dir-in-repo/" # optional
# USERNAME="github-username"
# PASSWORD="password-token"
# ----------
# Set files to auto backup
declare -a List=(
"/home/user/full/path/to/file.file"
"/home/user/.config/path/to/file.file"
)
source ./.env
REMOTE_REPO="github.com/username/reponame.git"
LOCAL_REPO="/home/user/local/reponame/"
SUBDIR_REPO="sub-dir-in-repo/" # optional
USERNAME="github-username"
PASSWORD=$MY_TOKEN
# <dir_of_sh>/log/YYYYMMDD.log is created.
PWD=$(pwd)
log_file=$PWD"/log/$(date +%Y%m%d).log"
mkdir -p $PWD"/log" && touch $log_file
# confirm SUBDIR_REPO exists
mkdir -p $LOCAL_REPO$SUBDIR_REPO
# main
echo "----- $(date +%Y/%m/%d-%H:%M:%S): $(basename "$0") -----" >>$log_file
cd $LOCAL_REPO
update_cnt=0
# check update for each item
for item in "${List[@]}"; do
# full/path/file to full_path_file
filename_full=$SUBDIR_REPO"${item//\//_}"
file1=$item
file2=$LOCAL_REPO$filename_full
echo "Update check: "$file1 >>$log_file
command1="date +%Y%m%d%H%M%S -r "$file1
command2="date +%Y%m%d%H%M%S -r "$file2
a=$(eval $command1)
b=$(eval $command2)
if [[ $a -eq $b ]]; then
echo " No update." >>$log_file
else
echo " Found update. Copy it to local repo. Git add, commit, push." >>$log_file
((update_cnt = update_cnt + 1))
cp -p $file1 $file2
$(eval "git add "$file2)
fi
done
if [[ $update_cnt -gt 0 ]]; then
git commit -m "Automatic back up"
git push -u https://$USERNAME:$PASSWORD@$REMOTE_REPO master >/dev/null 2>&1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment