GIT: When checking out an alternative branch, I want to clear ignored files

Assume I have a structure in master.

d - src 
      - main ...
      - resources ...
  - target
      - xyz

Files xyz should not be tracked, so I added into .gitignore target/*
and commit the structure

  • Subversion: Can I checkout, modify, and then make it a branch?
  • Netbeans fails on existing SVN copy (LWC), checked out with external SVN client
  • Does the folder I am in have any significance in git?
  • Why does Git tell me “Not currently on any branch” after I run “git checkout origin/<branch>”?
  • Get git current branch/tag name
  • GIT: commit changes to old/safe branch while in new/dirty/dev branch without checking out or losing unstaged data
    • git commit -m ‘initial structure’

    I create 2 branches

    • git branch t1
    • git branch t2

    and switch to t1

    I start doing some work, compile stuff, such that target is populated.
    I commit my changes to t1.

    • git commit -a ‘t1 specific changes’

    then I switch to t2

    • git checkout t2

    When I look into target, it is still populated with the files created
    when branch t1 was active, while I would like to have these ‘cleared out’

    I found a similar discussion stating that git should behave differently than I see. Git is deleting an ignored file when i switch branches

    What am I missing ?


  • git pull with gzip files in repo?
  • How to move issue within GitHub organization?
  • git status shows fatal: bad object HEAD
  • Apply patches created with git log -p
  • git log get range of commits starting with a tag
  • Git - merge from specific commit onwards
  • 3 Solutions collect form web for “GIT: When checking out an alternative branch, I want to clear ignored files”

    This is by design. Git will not touch files that it is not tracking in the working folder. If you want to clean the untracked files you can use

    git clean -xdf

    More commonly, I want to throw away changes that are not tracked but not ignored. This may be because I was experimenting with some code and added a new class file. In this case I would use:

    git clean -df

    This would leave my output directories as is. I would rely on my development tools to clean these folders instead.

    You could use the hook, but that’s not a good solution as it is harder to share across a team.

    You can add a post-checkout hook which cleans ignored files:

    git clean -f -X

    The question you linked is talking about a file that’s tracked in one branch and ignored in another. You’re talking about generated files that aren’t tracked in any branches. Since git isn’t tracking them, it won’t do anything to them.

    Git Baby is a git and github fan, let's start git clone.