Global gitignore

Tags: #git

11 September 2023

why I need a global gitignore file?

On a day to day basis, I work on some tools that requires project specific configuration. Two of the tools that I use on a daily basis with git repositories are:

  1. direnv ==> I use direnv to load project specific environment variables when I cd into a project directory with a .envrc file. This way I don't have to manage environment variables manually.

  2. Helix ==> This is the editor of my choice these days and I use it extensively. With the support of workspaces in helix, you can create a project specific helix configuration (./helix/config.toml) and make changes to your theme, keybindings etc. without affecting global configuration (~/.config/helix/config.toml).

In all those projects, it's useful to have a global .gitignore file that applies to all repositories. This way I'll be able to ignore certain file patterns in all of my git repo and maintain a clean git status output. In this post, I'll explain how to create a global gitignore file.

How to add global gitignore?

First you will have to select where do you want to store your global gitignore file and what name you want to give to that file. In my case, I have created a file called .gitignore_global in my home directory.

You can use the following command to create the file:

touch ~/.gitignore_global

After creating the file, you need to tell git to use this global gitignore file for all repositories. You can do this by setting the core.excludesfile configuration variable:

git config --global core.excludesfile ~/.gitignore_global

After executing the above command, you'll see that git added an entry for core.excludesfile in your global git configuration:

	excludesfile = /home/<user>/.gitignore_global

Here's how my ~/.gitignore_global looks like for me.

$ cat ~/.gitignore_global 

force adding files that are being ignored

Note: Sometimes on the personal project I also want to push my helix configuration to the repository to keep the config in sync across devices. In that case I can force add the helix config file. Let's look at man page of git add to see how we can force add files that are ignored via gitignore(local or global).

$ man git-add
    -f, --force
    Allow adding otherwise ignored files.

Now we know that we can force add files that are ignored via gitignore files by using git add -f <file>. To add .helix/config.toml

$ git add --force .helix/config.toml
$ git status --short 
A  .helix/config.toml

Now you see that the config was added even after gitignore ignoring it. If you changed your mind and if you don't want to add .helix/config.toml anymore than you can restore that using the command git restore --staged .helix/config.toml