Manage Your Dotfiles With Git

Git is an not only a great tool to version control the code you write but also to manage your configuration files for your machine. These files that are located in your home directory are often referred to as dotfiles. Since we do not want to put the whole home directory in a repository, we can use a so called bare git repository.

Initial Setup

To setup your dotfiles repo the first time, we initialise a bare repo with:

git init --bare $HOME/.dotfiles

We have to specify the git directory and the working tree to use with this bare repo. This can be simplified by adding an alias to your .gitconfig by typing

git config --global alias.dotfiles '!git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME'

Now we can simply type

git dotfiles <git command>

for example

git dotfiles status

to show the status of the files. At this point, git would show all the untracked files in the home directory. By typing

git dotfiles config --local status.showUntrackedFiles no

we can tell git to only show files that we added to the repo. The first file we should add is the .gitconfig file with

git dotfiles add .gitconfig
git dotfiles commit

We can now add a remote repository

git dotfiles remote add origin <remote repo>
# this is an example with my repo
git dotfiles remote add origin git@gitlab.com:codingcoffeebean/dotfiles.git

and push our first commit

git dotfiles push

Now you can add all dotfiles that you want to track.

Sync Dotfiles Across Machines

The remote repository can now be used to sync the dotfiles across multiple devices. On a new machine, simply clone the repo

git clone --bare <remote repo> $HOME/.dotfiles

and overwrite the existing dotfiles inside the home directory (be sure to backup the old files first, if you want to keep the old configuration)

git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME checkout -f