Using Global .gitignore on Mac

Using Global .gitignore on Mac

If you're a Git user, there is high chance you might be using .gitignore file to ignore certain files from being committed into your remote repo. Now, .gitignore file differs for different languages, frameworks and packages.

If you have several repositories maintaining multiple .gitignore files for them could be painful. Worst case, you can have multiple .gitignore file for several projects spanned across file system. Thanks for efforts of Git team, it is possible to maintain the global .gitignore file with common configuration across different projects.

For example, you may have projects in Swift, Objective-C, PHP, JavaScript or Ruby. You can maintain a single .gitignore with multiple rules combined in one place. Every time you commit, the global .gitignore will be referred and used.

First off, create a .gitignore_global file in the root directory of your project.

vi ~/.gitignore_global

Add some valid rules to it

Save the file content and exit. Now run the following on the command line

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

This will enable Git to mark this file as a global .gitignore which will subsequently be used to mark files to ignore in case no local .gitignore is found.

However, if you have both global and local .gitignore files, your git commit will take union of two files to decide which files to ignore. For example, let's assume you have git repo with 3 files.

  • sample1.txt
  • sample2.txt
  • sample3.txt

Now, let's see. Global .gitignore file specifies to exclude sample1.txt, local .gitignore file specifies to exclude sample2.txt. Thus the combined rule becomes exclude both sample1.txt and sample2.txt. Next time you commit, only sample3.txt file will be committed (Along with .gitignore unless it's been committed before) ignoring other two.

This should be it as long as basic understanding of creation and usage of global .gitignore file goes. If you want more information, you can always refer to GitHub official documentation on .gitignore files and also play with varied configurations.

However, use the global .gitignore with care and caution. It's super convenient when you're working alone. But in team environment it's possible everyone has their own copy of .gitignore and this has a potential to cause conflicts. The reason being global .gitignore is essentially local and personalized version of regular .gitignore. The best way to handle this conflict in team environment is to maintain local .gitignore file in every repository. That way if another team member makes changes to file, you will know which files to ignore in the next commit as long as you've pulled those changes from the remote branch

Reference:
GitHub official documentation