1

I am searching for an easier way to copy specific files and directories from 1 git branch to another without committing them.

Ex:

  • 2 branches - dev and prod
  • File service/web/company.html is present in both dev and prod branches. I want to copy this file from dev to prod, modify it a bit and then commit it to prod.

At the moment what I do is:

  • Clone the git repository 2 times into separate directories (git_dev & git_prod) and switch their branches (git checkout).

  • cp -f git_dev/service/web/company.html git_prod/service/web/company.html

There are files and directories currently committed to the dev branch that I want to copy to the prod branch, modify them and then commit them to the prod branch.

Subzero123
  • 47
  • 1
  • 6
  • 1
    First you say that you want to copy the files without committing them, and then you say that you want to commit to `prod`. Please clarify how this makes sense. – mkrieger1 Apr 03 '23 at 10:16

2 Answers2

2

Use git checkout for that:

  1. Switch to the branch where you want to copy to using

    git checkout <TARGET_BRANCH>
    
  2. "Check out" the files or directories from the branch you want to get them from with

    git checkout <SOURCE_BRANCH> <PATH>
    

It may be little bit confusing that you use checkout for both switching branches and getting files, but this is how it works. From official documentation on checkout subcommand:

git-checkout - Switch branches or restore working tree files

[...]

Updates files in the working tree to match the version in the index or the specified tree. If no pathspec was given, git checkout will also update HEAD to set the specified branch as the current branch.

Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28
  • 1
    Thanks, this is what I was looking for. One annoying thing is that it instantly stages it, so I have to unstage it, but I guess I can live with that. – Subzero123 Apr 03 '23 at 11:14
0

That is not the easiest to do it. You can checkout the target branch and ask git to get you the files as they are on the other branch:

git checkout prod
git restore --worktree --staged source=dev -- file1 file2
git commit -m "file1 and file2 as they are in dev right now"

There will be no relation to dev branch with that operation, by the way... it's just as if you had edited the files by hand to match dev branch content.

eftshift0
  • 26,375
  • 3
  • 36
  • 60