git-add - Linux


Overview

git add stages changes to the index in preparation for a commit. It ensures that the changes are tracked by Git and will be included in the next commit. Staging changes helps group related changes and ensures clean commits.

Syntax

git add [-A|-u|-p] [-f] [-i] [-v] [-e] [-n] <files/paths>...

Options/Flags

  • -A: Add all tracked files recursively.
  • -u: Only update the tracked files that have been modified since the last commit.
  • -p: Interactively stage hunks of changes in files.
  • -f: Force add files even if they are ignored by .gitignore.
  • -i: Interactive mode for adding files, prompting for confirmation.
  • -v: Verbose mode, showing what files are being added.
  • -e: Edit a file from the index before adding it.
  • -n: Dry run, show what files would be added without actually adding them.

Examples

  • Add all changes to the index:
git add -A
  • Add a specific file to the index:
git add myfile.txt
  • Interactively stage hunks of changes in a file:
git add -p myfile.txt
  • Force add an ignored file to the index:
git add -f ignored-file.txt

Common Issues

  • Error: pathspec ‘…’ did not match any files
    • The specified file or path does not exist or is ignored by .gitignore.
  • Error: not a valid object name ‘…’
    • The specified file is not tracked by Git.
  • Error: refusing to add an untracked directory
    • To add a directory, use git add -f or run git add from within the directory.

Integration

  • Use git commit to commit the staged changes to the repository.
  • Use git reset to unstage changes from the index.
  • Use git status to view the status of staged and unstaged changes.

Related Commands