You can use git rm –cached command to untrack files and directories that are already being tracked after adding gitignore.
gitignore file is used to ignore any files or directories that you don’t want git to track. Once you add a gitingore file containing details on files or directories that you want git to ignore, git will not track any new file or directory. But existing files or directories that are already being tracked by git will not get ignored. In this case, you need to remove git cache to ignore existing tracked files or directories.
On the other hand, you might want git to track a file or directory that is included in your gitignore file, use git add -f option in such cases.
Example:
Create a new local git repository:
1 2 |
## Create a new git local repository git init myrepo && cd myrepo |
Create a change and commit to your local repository default branch:
1 2 3 4 |
## Create first commit echo "cat" > file1 git add file1 git commit -m "commit1" |
Create a new file and directory and stage the changes:
1 2 3 |
## Create a new file and directory and stage the changes mkdir mydir && echo "dog" > myfile && echo "cow" > mydir/file2 git add . |
Add a .gitignore file that excludes the new file directory from being tracked:
1 2 |
## Add a gitignore file to exclude mydir, myfile and itself echo -e "myfile\n/mydir\n.gitignore" > .gitignore |
Check the git status:
1 2 3 4 5 |
## Check git status git status ## Changes to be committed: ## new file: mydir/file2 ## new file: myfile |
Observe: Though we have added a gitignore file to explicitly untrack the new file and directory, git is still tracking them. This happened as the new file and directory were already being tracked by git when we added the gitignore file.
Untrack existing tracked files and directories in git:
1 2 3 4 5 |
## Untrack existing tracked files and directories ## git rm --cached ## git rm -r --cached git rm --cached myfile git rm -r --cached mydir |
Check git status:
1 2 |
## Check git status git status ## nothing to commit, working tree clean |