Selectively git add Files
Learn to selectively git add files instead of choosing all files in the project folder.
In the project initialization steps, we learned to use git add .
to include all files in the project folder to the first git commit
. But most beginners only use git add .
for the rest of their lives. This command adds all files without reviewing them. We must use it carefully.
Overuse of git add .
If unrelated code is committed to the same commit, we won’t be able to review our history easily and then move back to a certain point in the past.
Selectively add files
When we work on two features at the same time, we should commit them separately. For example, we might concurrently implement a feature and fix a typo or a minor CSS style. This results in changes that belong to two different purposes:
- The first is the planned feature implementation.
- The other purpose is minor changes not related to the feature.
We can selectively add only specific files using git add <filename>
or git add <folder path>
.
Then, we git commit
with those added files only and repeat to commit the other files.
Selectively add code within a file
Occasionally, we have two feature changes in the same file. In that case, we need to add only part of the code within a file. To do so, we need git add -i
, which stands for “git add
interactively.”
Note: The
git add .
command means adding all the changes in the current directory. If we need all changes into the next commit, we can also combine the add and commit into one command:git commit -am "<MESSAGE>"
.
Suppose we have three files, but we only want to git add
the first and third files. We can do the following:
$ git add file1.txt file3.txt
$ git commit -m "Commit with File 1 and File 3."
We can verify by git status
command:
$ git status
Practice these commands in the terminal given below: