Git remote backups

Ash G - Jan 11 '21 - - Dev Community

As part of my development process, I've made a habit of keeping two remote repositories for every project I work on. One remote repository is on services such as Github, Gitlab etc. and second remote is on a separate/external hard disk.

It has saved me lot of hassle when I accidentally made some mistakes while committing or shouldn't have committed something in the first place and want to backtrack, and it's always good to have a backup, in case something goes wrong with your computer.

So here's how you do it:

  1. Create an empty repository i.e one without a working tree.
  2. Add the empty repository as a remote from your project's git repository.
  3. Push your changes to the empty repository.

Step 1: Create an empty repository i.e one without a working tree

You can create this repository anywhere you like, I usually create it on an external hard disk. Now open your terminal and run following command:

git init --bare /path/to/external_hdd/remote_backup.git
Enter fullscreen mode Exit fullscreen mode

Make sure you change the path above.

The --bare flag tells git to create a repository without a working tree because we won't be working with the files directly. We will only sync our changes with it.

Step 2: Add the empty repository as a remote from your project's git repo.

Add the remote_backup.git as a remote so we can push changes to it, it is just how we push changes to Github or any other git service you use.

git remote add backup /path/to/external_hdd/remote_backup.git
Enter fullscreen mode Exit fullscreen mode

Great, you can check by running following command that the remote was added correctly:

git remote -v
Enter fullscreen mode Exit fullscreen mode

Step 3: Push your changes to the empty repository

git push backup master
Enter fullscreen mode Exit fullscreen mode

I'm pushing master branch here, you can push changes from any branch, just like how you would push changes to Github.

That's it!

Whenever you make changes, push to both repositories.

I hope this tip comes in handy, especially to beginners who are starting out. I remember when I first started using git in a professional setting few years ago, I was afraid of making mistakes, but making mistakes is the first step in mastering something. All the best!

. . . . .