Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
HowTo have specific .gitignore for each git branch

How to have specific .gitignore for each git branch


My objective is to have some production files ignored on specific branches. Git doesn't allow to do it.


My solution is to make a general .gitignore file and add .gitignore.branch_name files for the branches I want to add specific file exclusion. I'll use post-checkout hook to copy those .gitignore.branch_name in place of .git/info/exclude each time I go to the branch with git checkout branch_name.


  1. Create new .gitignore files for each branch and name it like this : .gitignore.branch_name
  2. In your git repo, go to .git/hooks/
  3. Edit or create post-checkout file and copy the content found in this gist.
  4. Don't forget to make it executable with chmod 755 post-checkout
  5. Just go to the branch you want and type git status: TADAAA !
if [[ $branch_switched != '1' ]]
exit 0
echo "---- POST CHECKOUT ----"
current_branch=$(git rev-parse --abbrev-ref HEAD)
hook_dir=$(dirname $0)
root_dir="$(pwd -P)"
if [[ -f "$root_dir/$exclude_target.$current_branch" ]]
echo "Prepare to use .gitignore.$current_branch as exclude file"
cd "$info_dir"
rm exclude
#ln -s $exclude_target exclude
echo "Copy .gitignore.$current_branch file in place of exclude"
cp "$root_dir/$exclude_target" exclude
echo "--- POST CHECKOUT END ---"

This comment has been minimized.

Copy link

cxsper commented Sep 27, 2018

thanks, mate!


This comment has been minimized.

Copy link

tiagofrancafernandes commented Jan 2, 2020

Thank you!
I had a problem
.git/hooks/post-checkout: 7: .git/hooks/post-checkout: [[: not found
but solved using #!/bin/bash instead of #!/bin/sh.


This comment has been minimized.

Copy link

mluerig commented May 9, 2020

(please ignore my previous comments [deleted]- they were written on a friday afternoon when I was dumb and slow)

good stuff, works like a charm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.