Search code examples
gitgitignore

.gitignore is whitespace sensitive?


My .gitignore file seems to be working unpredictably. Here is an example:

I make a new repo foo with a file bar.txt, which I want to ignore:

pon2@kann4:~$ mkdir foo
pon2@kann4:~$ cd foo/
pon2@kann4:~/foo$ touch bar.txt
pon2@kann4:~/foo$ git init
Initialized empty Git repository in /home/pon2/foo/.git/
pon2@kann4:~/foo$ git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       bar.txt
nothing added to commit but untracked files present (use "git add" to track)

As expected, bar.txt shows up as untracked. So I tell git to ignore .txts, but I accidentally add some trailing whitespace:

pon2@kann4:~/foo$ echo "*.txt " > .gitignore

Now when I check the repo status, git doesn't ignore bar.txt:

pon2@kann4:~/foo$ git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       .gitignore
#       bar.txt
nothing added to commit but untracked files present (use "git add" to track)

What's going on?


Solution

  • .gitignore is whitespace sensitive. If you include trailing whitespace, git won't recognize your files.

    In this line there's a trailing space:

    pon2@kann4:~/foo$ echo "*.txt " > .gitignore
    

    Once we fix that:

    pon2@kann4:~/foo$ echo "*.txt" > .gitignore
    

    The issue resolves:

    pon2@kann4:~/foo$ git status
    # On branch master
    #
    # Initial commit
    #
    # Untracked files:
    #   (use "git add <file>..." to include in what will be committed)
    #
    #       .gitignore
    nothing added to commit but untracked files present (use "git add" to track)
    pon2@kann4:~/foo$