The git add
command is used for staging changes for the next commit. Specifically, it adds files and their contents to the "staging area". This is the place Git temporarily stores your changes before pushing them to the remote repository. The staging area lets you organize your changes locally before pushing and merging. Often however, you'll find yourself working with directories containing multiple files and subdirectories. This guide explains how to use git add
for recursively adding files, directories, and more.
Basic usage of git add
Before we explore recursive additions, let's review the basic usage of git add
:
- To stage a single file run:
git add filename.txt
- To stage multiple specific files:
git add file1.txt file2.txt
After running these commands, the specified files are added to the staging area and can then be pushed from your local machine to the remote Git server.
Recursively adding files and directories
Adding everything in your working directory
To add all changes in your current directory (including new files, modifications, and deletions), you can use:
git add .
This command stages all changes in the current directory and all subdirectories, effectively working recursively.
Adding specific directories recursively
To add all changes within a specific directory (and its subdirectories), specify the directory path:
git add path/to/directory/
This command recursively stages all changes within the specified directory.
Adding files with a specific extension
To add all files with a specific extension (e.g., .txt
) recursively from your current directory:
git add '*.txt'
The single quotes prevent the shell from expanding the wildcard (*
) before Git has a chance to interpret it, ensuring that Git searches all directories. This example will search the current directory and all of its subdirectories for every file ending in '.txt', and then add those files to the staging area.
git add
can also match more complex patterns like:
git add '*pattern*'
This command adds all files in the current directory and subdirectories that contain the string "pattern" anywhere in their filenames.
Staging new files and modifications, excluding deletions
If you want to stage new files and modifications but exclude deletions:
git add --ignore-removal .
This command tells Git to ignore removed files while staging changes recursively. The removed files will still be removed locally but those deletions will not be reflected in any pushes to remote.
Additional options
Dry run: Before actually staging files, you can perform a "dry run" with
git add -n
. This will show you what would be added without actually adding it, providing a chance to review changes.Terminalgit add -n .
For further reading on how to add files in Git, see the official documentation.