The git add
command is a fundamental part of the Git version control system, serving as the first step in the three-stage process of making changes to your repository.
Running git add
adds the target data to the “staging area”. Also referenced as the cache or index, the staging area is where files are temporarily stored before they are included as part of the next commit. This is how Git understands what's going to change between the current commit, or the HEAD, and the next commit.
This guide will explain how to use git add
effectively. It will show you how to add single files, multiple files, directories, and more.
Basic use of Git add
Adding a single file with
git add
: The basic syntax for adding a file to the staging area is:git add <file-name>
Replace
<file-name>
with the name of the file you want to stage.Git add all files: To add all of the changes in your local working directory (including new, modified, and deleted files) to the staging area, run:
git add .
The period
.
represents the current directory. If you wish to add every change within the scope of the repo make sure you navigate to the root of the Git repository.
Additional ways to use the git add command
Git add directory: To recursively add all files inside a directory (including all subdirectories), specify the directory path:
git add <directory-path>
Git add multiple files: You can stage multiple specific files at once by listing their file-paths:
git add <file1> <file2> <file3>
Git add all modified files: To stage all modified files without adding untracked (new) files, use:
git add -u
Advanced Git add techniques
Git add by glob pattern: You can use patterns to add files. For example, to add all
.txt
files:git add '*.txt'
When using pattern matching, it’s helpful to use the
--dry-run
flag to see exactly which files will be staged before actually adding them.Git add chunks: For more control, you can add changes in chunks using:
git add -p
This command allows you to review your changes in small chunks across all of your different files. This is particularly useful for catching leftover scratch work like “TODOs” for example, and lets you be more intentional when adding changes to staging.
Best practices and additional information
Understanding
git add .
vsgit add -A
: Whilegit add .
adds all changes in the current directory,git add -A
adds all changes in the entire repository. Be mindful of your current directory when using these commands.Git add before commit: It’s best practice to always review your changes with
git status
before runninggit add
to avoid staging unintended changes.Documentation and Help: For more detailed information on
git add
and its options, you can consult the use the help command:git add --help
or visit the official Git documentation for further reading.