I would use git restore
(available since Git 2.23):
git restore --source otherbranch path/to/myfile.txt
Why is this better than other options?
- by default
git restore
modifies files only in the working directory
git checkout otherbranch -- path/to/myfile.txt
copies the file to the working directory (your files on disk) but also to the staging area. It has the same effect as if you copied the file manually and executed git add
on it. git restore
by default changes only the working directory.
To get the same result as for git checkout otherbranch -- path/to/myfile.txt
you can write git restore --source otherbranch --staged --worktree path/to/myfile.txt
- by default
git restore
deletes files from the working directory when they are absent in the other branch
git restore
can be used to restore the whole folder with git restore --source otherbranch path/to/dir
. You can do a similar operation with git checkout
but git restore
by default will delete files that are absent in otherbranch
. To get git checkout
behaviour use --overlay
option.
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 a good default behaviour because you most likely want the state of the directory to be "the same as otherbranch
", not "the same as otherbranch
but with additional files from my current branch".
To really get the same result as for git checkout otherbranch -- path/to/dir
you can write git restore --source otherbranch --staged --worktree --overlay path/to/dir
git restore
doesn't use shell redirection to create file (Powershell only problem)
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 could result in a corrupt file if it's binary (update: fixed in PowerShell 7.4). With git restore
changing files is done all by the git
executable.
git restore --source otherbranch path/to/myfile.txt
(see explanation in the answer). – Tahr