Git Ignore indexed file but cannot switch to a branch if it’s modified

eye-catch Other techs

When we add a path to a directory or a file in .gitignore file, changes to those files are ignored. But sometimes we want to add the file to our repository to share for example environment values .env. In this case, we forcibly commit the file.

Some might think that the future changes to those files are ignored because the path is included in .gitignore but actually not. All changes to the files are not ignored and thus the files are listed in the changed list.

If we want to ignore them, the following command is a solution.

git update-index --skip-worktree <file path>
# example
git update-index --skip-worktree .env

However, if we update the file and want to switch to another branch that doesn’t contain the ignored file, it fails to switch.

$ git switch -f <branch-name>
error: Entry '.env' not uptodate. Cannot merge.

Hmm… I couldn’t find a beautiful solution.

This is my solution. We need to revert the process in this case.

git update-index --no-skip-worktree <file path>
git stash
git switch <branch>

The target file is added to the index tree again with the first command. Then, stash the change. After that, we can finally switch the branch.

Comments

Copied title and URL