Storing dotfiles with bare git repository

Storing dotfiles with bare git repository

You've probably come across a situation where you had multiple machines and encountered the hassle of rewriting config files because you neglected to back them up for some inexplicable reason. Of course, there are alternative solutions for safeguarding your dotfiles. However, in this step-by-step guide, we'll delve into a rather peculiar approach that involves utilizing git as a means to back them up.

Step 1: Initialize git bare repository

A git bare repository does not have a working directory associated with it. Unlike a regular git repository, which includes both the version-controlled files and the working directory where you can modify and view the files, a bare repository only contains the version history and the repository's metadata.
  1. Create a new remote repository called dotfiles.

  2. Clone newly created repository locally. Notice the --bare flag.

$ git clone --bare <git-repo-url> $HOME/.cfg

Step 2: Create an alias to avoid conflict

config is an alias for git to avoid running commands on local .git directory when you mean to run commands on .cfg.

$ echo "alias config='/usr/bin/git --git-dir=$HOME/.cfg/ --work-tree=$HOME'" >> $HOME/.zshrc
$ source ~/.zshrc

Step 3: Hide files that are not required to be tracked

By default, all files from your $HOME directory will be tracked which you do not want. To turn off the tracking of unnecessary files you'll need to do the following.

$ config config --local status.showUntrackedFiles no

After which your $HOME/.cfg/config file should look like below. The [status] part is appended after running above command.

        repositoryformatversion = 0
        filemode = true
        bare = true
        ignorecase = true
        precomposeunicode = true
        showUntrackedFiles = no

On running config status you should not see unnecessary files being tracked.

Step 4: Add dotfiles and push

$ config add ~/.zshrc
$ config commit -m "Add zshrc"
$ config push -u origin main

Installing dotfiles on new machine

Follow the first 3 steps from above.

$ config checkout

If dotfiles are already existing on the new machine then it'll show a conflict. In that case, you can delete or rename those files first.

Now, you can add edit your dotfiles and push to origin and follow same process on any machine to get your dotfiles.