How to get a file from a different branch?
Please pay attention to update your answer.
Update Your Answer care fully. After saving you can not recover your old answer
If you’re using Git 2.23+, you can pull a single file from another branch without merging or switching branches. the git restore command provides a safer and more readable way to restore files from another branch, commit or state without switching branches or merging changes.
If you want to copy only one file (e.g., experiment.js) from another branch (feature-experiment-1) into your current branch (feature-experiment-2), follow these steps:
# Make sure you're on your current branch
git checkout feature-experiment-2
# Restore only the needed file
git restore --source feature-experiment-1 path/to/experiment.js
# Stage and commit it
git add path/to/experiment.js
git commit -m "Restored experiment.js from feature-experiment-1" Use when: you want just one file from another branch, not all its changes.
Safer and cleaner than git checkout.
Please pay attention to update your answer.
Update Your Answer care fully. After saving you can not recover your old answer
Switch to the target branch where you need the file
git checkout feature-experiment-2
Copy the specific file from another branch
git checkout feature-experiment-1 -- experiment.js
Stage the file
git add experiment.js
Commit the changes
git commit -m "picked experiment.js from feature-experiment-1 branch"
Please pay attention to update your answer.
Update Your Answer care fully. After saving you can not recover your old answer
If you want to get just one file (like experiment.js) from another branch (feature-experiment-1) without merging the whole branch, use:
git checkout feature-experiment-1 -- path/to/experiment.js
Example:
git checkout feature-experiment-1 -- src/experiment.js
This will:
- Bring only that file’s version from
feature-experiment-1 - Leave all other files in your current branch (
feature-experiment-2) untouched
After that
If you want to commit it:
git add src/experiment.js
git commit -m "Pulled experiment.js from feature-experiment-1"Please pay attention to update your answer.
Update Your Answer care fully. After saving you can not recover your old answer
If the experiment.js update was made in a specific commit, you can apply only that commit’s changes to your current branch:
git cherry-pick <commit-hash> --no-commit
What it does:
This command pulls the changes from the given commit into your current branch without immediately committing them allowing you to review or edit before finalizing.
Use this when:
You need only one commit’s changes (like updates to experiment.js) without merging all other files from another branch.
Then finalize the change:
git add path/to/experiment.js
git commit -m "Applied experiment.js update from feature-experiment-1"