Backup Files with Git

A basic guide to backing up files/directories using git.

Debian/Ubuntu installation:

sudo apt update
sudo apt install git

CentOS installation:

sudo yum install git

You will now need to determine the directory that will be the git “project”.

  1. CD to the into the directory you want to be backed up.
    cd /path/to/directory
  2. Initialize the git “project”
    git init
  3. Setup git name for author (If this will be an automated task, use the name of the service/program that will be backed up such as “nginx” or “wiki”)
    git config –global user.name “Your Name”
  4. Setup git email for author (This can be your email or a service account email if one exists)
    git config –global user.email you@example.com
  5. Set git to store the username and password for automation purposes
    git config –global credential.helper store
  6. Add all of the files into the project
    git add .
  7. Set an initial commit with a commit message
    git commit -a -m “Initial Commit”
  8. Add the remote repository to backup the files to (replace the url with the url for your repository)
    git remote add origin https://gitlab.nkcyber.org/user/project.git
  9. You will then be asked for the username and password, this is the gitlab/github user that has access to the remote repository

You now have backed the files up to the remote repository manually.

This is to configure automatic backups that will occur daily at 3am. First, create a backup shell script as follows:

cd /path/to/directory && git add . && git add -u && git commit -a -m "Content update `date +'%H:%M %d/%m/%Y %Z'`" && git push origin master

Next, create a cron task that will occur once a day at 3am:

crontab -e

# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
# │ │ │ │ │   7 is also Sunday on some systems)
  0 3 * * * /path/do/directory/backup.sh>> /var/log/backup.log

The script should now run at 3am everyday and output a log to /var/log/backup.log

  • other/backupgit.txt
  • Last modified: 2020/09/11 06:55
  • by nkzeb01