Method 1: Using git checkout (Easiest)
This method copies the file’s content into your working directory and stages it automatically, as if you manually copied the file and ran git add.
- Switch to your target branch (the branch where you want the file to go):bash
git checkout <target_branch_name> - Copy the file from the source branch using
git checkout <source_branch> -- <path_to_file>:bashgit checkout <source_branch_name> -- <path/to/file.txt>- The
--is a crucial separator that tells Git you are done with options and branch names, and what follows is a file path (pathspec).
- The
- Commit the change:bash
git commit -m "Copied file.txt from <source_branch_name>"
Method 2: Using git restore --source (Modern Alternative)
This is a modern alternative to git checkout for restoring working tree files. By default, it only changes the working directory, leaving the staging area untouched unless you use the --staged option.
- Switch to your target branch:bash
git checkout <target_branch_name> - Copy the file from the source branch using
git restore:bashgit restore --source <source_branch_name> <path/to/file.txt>- To copy an entire directory, you can use
git restore --source <source_branch_name> <path/to/directory>.
- To copy an entire directory, you can use
- Stage and commit the change manually, as
git restoredoesn’t stage by default:bashgit add <path/to/file.txt> git commit -m "Copied file.txt from <source_branch_name>"
Method 3: Using git cherry-pick (To preserve commit history)
If you want to copy a specific commit and its message (which includes changes to one or more files) from another branch to your current one, use git cherry-pick.
- Find the commit hash of the commit that introduced the file or specific changes you want to copy:bash
git log <source_branch_name>- Make a note of the commit hash (e.g.,
a1b2c3d4).
- Make a note of the commit hash (e.g.,
- Switch to your target branch:bash
git checkout <target_branch_name> - Apply the commit using
git cherry-pick:bashgit cherry-pick <commit_hash>- If there are conflicts, Git will prompt you to resolve them before completing the cherry-pick.
Summary of Commands
| Method | Command | Effect | Preserves History |
|---|---|---|---|
| Checkout | git checkout <source_branch> -- <path/to/file.txt> | Copies file to working directory & stages it | No (creates new commit) |
| Restore | git restore --source <source_branch> <path/to/file.txt> | Copies file to working directory (unstaged) | No (creates new commit) |
| Cherry-pick | git cherry-pick <commit_hash> | Applies an entire commit to current branch | Yes (via cherry-pick commit) |
