I would use git restore
(available since Git 2.23):
git restore --source otherbranch path/to/myfile.txt
Why is it better than other options?
git checkout otherbranch -- path/to/myfile.txt
- It copy file to working directory but also to staging area (similar effect as if you would copy this file manually and executed git add
on it). git restore
doesn't touch staging area (unless told it to by --staged
option).
git show otherbranch:path/to/myfile.txt > path/to/myfile.txt
uses standard shell redirection. If you use PowerShell then there might be problem with text encoding or you could get broken file if it's binary. With git restore
changing files is done all by the git
executable.
Another advantage is that you can restore the whole folder with:
git restore --source otherbranch path/to
or with git restore --overlay --source otherbranch path/to
if you want to avoid deleting files. For example, if there are fewer files on otherbranch
than in the current working directory (and these files are tracked) without --overlay
option git restore
will delete them. But this is good default behaviour, you most likely want the state of directory to be "the same like in otherbranch
", not "the same like in otherbranch
but with additional files from my current branch".
git restore --source otherbranch path/to/myfile.txt
(see explanation in the answer). – toraritte