Copy one file from another Git branch
Bring a file or directory into your current branch, choose whether to stage it, and avoid confusing a snapshot replacement with a merge.
Use git restore --source=feature-x -- path/to/file to replace the working copy with that branch's version. Add --staged --worktree if you also want the replacement staged. The older git checkout feature-x -- path/to/file updates both the index and working tree.
Copy, inspect, and commit
Start on the destination branch and save local changes to the selected file before overwriting them:
git switch main
git restore --source=feature-x -- src/utils/helper.js
git diff -- src/utils/helper.js
git add -- src/utils/helper.js
git diff --cached -- src/utils/helper.js
git commit -m "Import helper implementation from feature-x"
The restore command above does not stage automatically. To stage the replacement immediately, use:
git restore --source=feature-x --staged --worktree -- src/utils/helper.js
# Older syntax, for a file present in the source:
git checkout feature-x -- src/utils/helper.js
Review the rest of the index before committing: a plain commit includes all staged changes, not just the copied file.
Use directories, old commits, or remote refs
git restore --source=feature-x -- src/components/
git restore --source=a1b2c3d -- src/app.js
git show feature-x:src/app.js
git fetch origin
git restore --source=origin/feature-x -- src/app.js
git show prints the stored content without modifying either copy. A remote-tracking ref is a local snapshot refreshed by fetch; the fetch configuration must include that branch.
Restore normally removes tracked paths absent from the source. Traditional checkout defaults to overlay behavior instead, so copying a directory with the two commands can differ when the source lacks some destination files.
Choose hunks or undo the replacement
Use git restore -p --source=feature-x -- path/to/file to select working-tree hunks. The legacy git checkout -p feature-x -- path/to/file can also update the index, so inspect both diffs afterward.
To discard the replacement and reset both copies to the current commit:
git restore --source=HEAD --staged --worktree -- path/to/file
That restores HEAD, not any uncommitted state that existed before the copy. Recover that earlier state from the backup or stash you made.
Does this merge the file's history?
No. This replaces a snapshot; the eventual commit belongs to the destination history. To combine independent edits, merge them deliberately or cherry-pick the relevant commits and resolve conflicts. Copying a file does not establish an ancestry relationship with its source branch.
See git-restore and git-checkout.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan