Combine with Ignored Files Check
In the previous steps, we learned how to identify untracked files using git status
and git ls-files --others
. However, sometimes you have files that you intentionally don't want Git to track, like temporary files, build outputs, or configuration files containing sensitive information. Git allows you to specify these files in a .gitignore
file.
In this step, we will create a .gitignore
file and see how it affects the output of git status
and git ls-files --others
.
First, make sure you are in the ~/project/my-time-machine
directory.
Now, let's create a file that we want to ignore. We'll call it temp.log
:
echo "This is a temporary log file" > temp.log
Run git status
again:
git status
You should see both notes.txt
and temp.log
listed as untracked files:
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: message.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
notes.txt
temp.log
no changes added to commit (use "git add" and/or "git commit -a")
Now, let's create a .gitignore
file and add temp.log
to it. Use the nano
editor to create and edit the file:
nano .gitignore
Inside the nano
editor, type the following line:
temp.log
Press Ctrl + X
, then Y
to save, and Enter
to confirm the filename.
Now, run git status
one more time:
git status
This time, temp.log
should no longer appear in the "Untracked files:" list:
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: message.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
notes.txt
no changes added to commit (use "git add" and/or "git commit -a")
Git now knows to ignore temp.log
. Let's also see how git ls-files --others
is affected:
git ls-files --others
The output should now only show notes.txt
:
notes.txt
By default, git ls-files --others
does not list ignored files. This is usually the desired behavior, as you typically don't want to see files you've explicitly told Git to ignore.
If you do want to see ignored files along with other untracked files, you can use the --ignored
option with git ls-files --others
:
git ls-files --others --ignored
The output will now include both untracked and ignored files:
.gitignore
notes.txt
temp.log
Note that .gitignore
itself is an untracked file until you add and commit it.
Understanding how to use .gitignore
is crucial for keeping your repository clean and focused on the actual project files. It prevents accidental commits of files that shouldn't be in version control.