git restore, git restore --source
git restore [<options>] [--source=<tree-ish>] [--] <pathspec>...
git restore --source=HEAD -- <file>Replace the working tree copy of a file, by default from the index, which can discard uncommitted edits.
| Parameter | Description |
|---|---|
<pathspec> | The files to restore. Use -- before a path that could look like an option. |
--source=<tree-ish> | The tree to copy from. When omitted and only the working tree is restored, the source is the index. |
--worktree / -W | Restore the working tree. This is the default when --staged is not given. |
Returns: The selected files in the working tree are overwritten with the source content. There is no stash of the previous working-tree bytes.
- This is a destructive working-tree operation. Check git diff and git status first. The default source is the index, so restore is not always "go back to the last commit".
- Git 2.39.5 does not provide git restore --dry-run.
git init -b main >/dev/null
git config user.name "Practice Author"
git config user.email "[email protected]"
git config commit.gpgsign false
git config color.ui false
mkdir -p .disabled-hooks
git config core.hooksPath ".disabled-hooks"
printf 'head\n' > f.txt
git add f.txt
git commit -m "HEAD content" >/dev/null
printf 'staged\n' > f.txt
git add f.txt
printf 'worktree\n' > f.txt
echo "before $(cat f.txt)"
git status --porcelain=v1
git restore f.txt
echo "default $(cat f.txt)"
git status --porcelain=v1
printf 'worktree\n' > f.txt
git restore --source=HEAD -- f.txt
echo "source-HEAD $(cat f.txt)"
git status --porcelain=v1
Expected output
before worktree
MM f.txt
default staged
M f.txt
source-HEAD head
MM f.txt
Related: git status, git stash