git add and git add --patch
- Version
- 2.51
- Review
- Draft
Summary#
git add copies the current content of the named paths into the index, which holds the next commit. --patch walks through the differences one hunk at a time so you can stage some edits and leave others in the working tree.
Syntax#
git add -- path/to/file
git add --patch -- path/to/file
git add --intent-to-add -- new-file
Example#
(
set -eu
scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
trap 'rm -rf -- "$scratch"' EXIT
unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
export GIT_PAGER=cat GIT_EDITOR=true
mkdir "$scratch/work"
cd "$scratch/work"
git init -q -b trunk
git config user.name "Reference Example"
git config user.email example@example.invalid
printf '%s\n' one two three four five six seven eight nine ten > list.txt
git add list.txt
git commit -qm "Add list"
printf '%s\n' ONE two three four five six seven eight nine TEN > list.txt
# Answer the two hunk prompts: stage the first, skip the second.
printf 'y\nn\n' | git add --patch -- list.txt > /dev/null
echo "staged:"
git diff --cached -U0 -- list.txt | grep '^[+-][^+-]'
echo "unstaged:"
git diff -U0 -- list.txt | grep '^[+-][^+-]'
)
Expected output#
staged:
-one
+ONE
unstaged:
-ten
+TEN
Common mistakes#
Patch mode compares the index with the working tree, so it reports no changes for an untracked file. Run git add -N on the file first, then use -p. Also remember that a partially staged snapshot may never have existed on disk, so test it before relying on it.
Version applicability#
Git 1.5.4 added git add -p. Git 1.6.1 added -N for intent to add. The example answers each prompt with a line on standard input; at a terminal you type the answers.
The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0