How to copy a file from one Git branch to another
If you need to copy a file from one Git branch to another, there's a simple solution using git switch
and git restore
. Here's the basic process:
# First, switch to the target branch
git switch <my-branch>
# Then, restore the file from the source branch
git restore --source <source-branch> -- file/to/restore
For example, let's say you want to copy the file config.js
from the master
branch to your new-feature
branch. You can use the following commands:
git switch new-feature
git restore --source master -- config.js
This technique is particularly useful when you are working on a web app and updating dependencies in the package.json
. Sometimes the master
branch may receive updates to dependencies, while your branch is still open.
This can result in conflicts between your local package-lock.json
and the one from the master
branch.
To resolve this issue, simply copy the package-lock.json
from the master
branch:
git switch my-branch
git restore --source master -- package-lock.json
After copying the package-lock.json
file, run npm install
to update it.
It's worth noting that the --source
flag accepts not only branches but also specific commits or tags.