Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'!' does not exclude file in .gitignore

Tags:

git

gitignore

my .gitignore file:

.DS_Store
temp
!temp/script.txt

However when I do git status it doesn't display the temp/ directory to indicate that the script.txt is not in staged. It only displays the .gitignore file:

# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   .gitignore

I'm just learning git. Any idea where i'm going wrong?

like image 981
kaizenCoder Avatar asked Feb 11 '26 15:02

kaizenCoder


1 Answers

Replace temp with:

temp/*

This ignores all files in the directory. In most cases temp, temp/ and temp/* all work the same because in the first two cases, the directory is ignore while in the third case, Git does not track empty directories. Thus, the directory itself will be ignored.

To illustrate this, this is essentially what happens when temp/ has temp1.txt temp2.txt temp3.txt:

temp # anything with the name of "temp"; a directory, a symlink, a file.
temp/ # whole of temp dir
temp/* # temp/temp1.txt temp/temp2.txt temp/temp3.txt

Thus, the third case will work in your case.

The negation pattern must be placed after the pattern that covers it. In this case, !temp/script.txt must come after temp/*. Otherwise, it will not be applied.

So, your final .gitignore file should look like this:

.DS_Store
temp/*
!temp/script.txt
like image 138
wei2912 Avatar answered Feb 13 '26 18:02

wei2912



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!