In Git, the add command is used to stage files for inclusion in the next commit. This process allows you to prepare changes or new files before they are permanently recorded in Git’s version history. Let’s explore how to effectively use the git add command with various examples.
Example 1: Adding a single file named script.js
to the staging area:
$ git add script.js
This command stages the script.js
file for the next commit.
Verification: To verify, run git status
and check if script.js
appears under “Changes to be committed”.
Example 2: Adding all files and changes under the current directory to the staging area:
$ git add .
This command stages all files and changes in the current directory.
Verification: Run git status
to confirm all modified files are staged.
Example 3: Using interactive mode to selectively stage parts of a file:
$ git add -p
This command allows you to interactively stage chunks or lines of changes within files.
Verification: After using git add -p
, review staged changes with git diff --cached
.
Example 4: Adding files with a specific extension, such as all .txt
files:
$ git add '*.txt'
This command stages all files with the .txt
extension.
Verification: Check with git status
and ensure all .txt
files are listed as staged.
Example 5: Adding files from a specific subdirectory, like docs/
:
$ git add docs/
This command stages all files and changes within the docs/
directory.
Verification: Use git status
to verify changes from the docs/
directory are staged.
Example 6: Adding changes from tracked files, including deletions:
$ git add -u
This command stages modifications and deletions of tracked files.
Verification: Check with git status
to see modified files are staged for the commit.
Example 7: Adding a file with renaming it in the same commit:
$ git add oldname.txt newname.txt
This command stages the renaming of oldname.txt
to newname.txt
.
Verification: Verify with git status
and ensure the rename is staged correctly.
Example 8: Adding ignored files by force:
$ git add -f ignoredfile.log
This command stages ignoredfile.log
even though it’s listed in .gitignore
.
Verification: Confirm with git status
that ignoredfile.log
is staged.
Example 9: Adding changes interactively with a specific patch size:
$ git add -i --patch
This command interactively stages changes, allowing you to choose patches to stage.
Verification: After interaction, review staged changes with git diff --cached
.
Example 10: Adding changes and skipping the pre-commit hook:
$ git add --no-verify .
This command stages changes while bypassing any pre-commit hooks configured in the repository.
Verification: Verify with git status
that all changes are staged despite the hook bypass.
Discussion about this post