git checkout | git restore | git cherry-pick

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

  1. Switch to your target branch (the branch where you want the file to go):bashgit checkout <target_branch_name>
  2. 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).
  3. Commit the change:bashgit 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. 

  1. Switch to your target branch:bashgit checkout <target_branch_name>
  2. 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>.
  3. Stage and commit the change manually, as git restore doesn’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

  1. Find the commit hash of the commit that introduced the file or specific changes you want to copy:bashgit log <source_branch_name>
    • Make a note of the commit hash (e.g., a1b2c3d4).
  2. Switch to your target branch:bashgit checkout <target_branch_name>
  3. 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 CommandEffectPreserves History
Checkoutgit checkout <source_branch> -- <path/to/file.txt>Copies file to working directory & stages itNo (creates new commit)
Restoregit restore --source <source_branch> <path/to/file.txt>Copies file to working directory (unstaged)No (creates new commit)
Cherry-pickgit cherry-pick <commit_hash>Applies an entire commit to current branchYes (via cherry-pick commit)

Leave a Reply