Git Add
The git add command puts your changes in the staging area. Git will include only the staged changes in the next commit. If you do not add a file, it will not go to the commit.
Syntax
git add <file>
git add <folder>
git add .
git add -A
git add -u
Add one file
$ mkdir site
$ cd site
$ git init -q
$ echo "Home" > index.html
$ echo "About" > about.html
$ echo "body {}" > style.css
$ git status -s
?? about.html
?? index.html
?? style.css
$ git add index.html
$ git status -s
A index.html
?? about.html
?? style.css
The first ?? means the file is untracked. After git add, it shows A (added to the staging area).
Add files by a pattern
You can use a wildcard to add many files with the same extension. The shell expands the pattern, so this works like writing all names.
$ git add *.html
$ git status -s
A about.html
A index.html
?? style.css
Add everything with a dot
$ git add .
$ git status -s
A about.html
A index.html
A style.css
The dot (.) means the current folder, so all new and changed files in this folder and its sub folders are added.
git add . vs git add -A vs git add -u
The difference is clear when we have a modified file, a deleted file and a new file together. First we commit, then make the three changes.
$ git commit -q -m "First version"
$ echo "Home page v2" > index.html
$ rm about.html
$ echo "todo" > notes.txt
$ git status -s
D about.html
M index.html
?? notes.txt
$ git add -u
$ git status -s
D about.html
M index.html
?? notes.txt
git add -u stages only the tracked files (modified and deleted). The new file notes.txt is still untracked. Now we use -A:
$ git add -A
$ git status -s
D about.html
M index.html
A notes.txt
| Command | New files | Modified files | Deleted files |
|---|---|---|---|
git add . | Yes | Yes | Yes (Git 2.0 and later) |
git add -A | Yes | Yes | Yes (whole repository) |
git add -u | No | Yes | Yes |
git add file | Only that file | Only that file | Only that file |
Add parts of a file
Sometimes one file has two different changes, and you want to commit them separately. The patch mode lets you choose the parts (called hunks) one by one.
git add -p index.html
Git will ask for each hunk. You type y to stage it, n to skip it, or s to split it into smaller parts.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |