You can force add ignored files or directories included in gitignore file using git add -f command.
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.
Example:
Create a new git local 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" |
Add a gitignore file to exclude mydir, myfile and itself:
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 |
## Check git status git status # nothing to commit, working tree clean |
Create a new file and directory included in your gitignore file:
1 2 |
## Create a new file and directory and stage the changes mkdir mydir && echo "dog" > myfile && echo "cow" > mydir/file2 |
Check the git status:
1 2 |
## Check git status git status # nothing to commit, working tree clean |
Observe: Since the new file and directory are added in the exclusion list of your gitignore file they were not being tracked by git.
Stage the new file and directory and check if they are being tracked:
1 2 3 4 5 |
## Add the changes in staging area git add . ## Check git status git status # still nothing to commit, working tree clean |
Observe: Since the new file and directory are added in the exclusion list of your gitignore file they were not being tracked by git.
Track files and directories included in gitognore file:
1 2 3 |
## force add the changes in staging area git add -f mydir/file2 git add -f myfile |
Now 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: Since we have forcefully added the new file and directory, they are being tracked by git though included in .gitignore file.