Getting Git

A comprehensive video course from git init to Git Master.

Master: git add

In this video, we'll learn some of the additional options for git add.

We covered how to add individual files and multiple files in the init video.

Now, let's master some of the nuances of git add as well as its additional options.

git add . has two nuances.

First, it only adds files under the current directory. So, if you run git add . within a sub directory, it won't add changes to files outside that sub directory.

Second, git add . adds both tracked and untracked files.

Let's demonstrate this, by creating a file in the current directory as well as a file in a sub-directory.

Now let's change into the sub-directory and run git add .

If we run git status, we'll notice only the file in the sub-directory was added.

You can avoid by using git add -A. This will add all changes to all files within the Git repository, regardless of our current directory.

Let's create another file in the sub-directory to demonstrate this.

Now run git add -A.

This time, git status shows us all files were added.

Since git add -A adds all the things, it a rather heavy-handed command.

For example, you might not want to add untracked files.

In which case, you can use git add -u to skip untracked files and only add tracked files.

While each of these options has their use, the option I use the most is git add -p.

The -p stands for patch.

git add -p will gather all changes in tracked files and allow you to review them interactively.

Let's demonstrate by making some changes to a couple of the files.

Let's just add a few lines to File 1 and a line above and below the content in File 2.

Running git add -p will open a command prompt where we can tell Git what to do with each change.

There are several options, we can type y to add the change and continue to the next change.

We can type s to split the current change into smaller changes.

We can type n to not add the change.

And at anytime we can type q to quit.

I prefer git add -p not only because it gives me full control of what changes are added, but also because it provides a chance to review my changes.

More often than not, I'll find I left a debugging statement or some other change I don't want to add.

Regardless of which option you prefer, git add will be one of the Git commands you use most.

So take the time to master each of them and run git help add for more details.