1758

I am using Git and working on master branch. This branch has a file called app.js.

I have an experiment branch in which I made a bunch of changes and tons of commits. Now I want to bring all the changes done only to app.js from experiment to master branch.

How do I do that?

Once again I do not want a merge. I just want to bring all the changes in app.js from experiment branch to master branch.

Paulo Mattos
  • 17,605
  • 10
  • 69
  • 79
Nick Vanderbilt
  • 34,224
  • 27
  • 82
  • 104
  • 18
    this is a duplicate of [How do I copy a version of a single file from one git branch to another?](http://stackoverflow.com/questions/307579/how-do-i-copy-a-version-of-a-single-file-from-one-git-branch-to-another) – givanse Jan 02 '14 at 20:32
  • 1
    Excepted answer and others as of today answer how to copy file's contents, that's what I wanted myself when I found that one. However, if read exactly, Nick wanted to bring changes, not full text, and file in `master` may diverge from `experiment`, e.g. can contain changes merged from other branches which would be lost in file is just copied. P.S. on the other hand he does not want to merge, but as far as I know `git merge` term is for branch only, not for specific file, so no contradiction here. – Alexei Martianov Apr 11 '19 at 07:47

14 Answers14

2171
git checkout master               # first get back to master
git checkout experiment -- app.js # then copy the version of app.js 
                                  # from branch "experiment"

See also git how to undo changes of one file?


Update August 2019, Git 2.23

With the new git switch and git restore commands, that would be:

git switch master
git restore --source experiment -- app.js

By default, only the working tree is restored.
If you want to update the index as well (meaning restore the file content, and add it to the index in one command):

git restore --source experiment --staged --worktree -- app.js
# shorter:
git restore -s experiment -SW -- app.js

As Jakub Narębski mentions in the comments:

git show experiment:path/to/app.js > path/to/app.js

works too, except that, as detailed in the SO question "How to retrieve a single file from specific revision in Git?", you need to use the full path from the root directory of the repo.
Hence the path/to/app.js used by Jakub in his example.

As Frosty mentions in the comment:

you will only get the most recent state of app.js

But, for git checkout or git show, you can actually reference any revision you want, as illustrated in the SO question "git checkout revision of a file in git gui":

$ git show $REVISION:$FILENAME
$ git checkout $REVISION -- $FILENAME

would be the same is $FILENAME is a full path of a versioned file.

$REVISION can be as shown in git rev-parse:

experiment@{yesterday}:app.js # app.js as it was yesterday 
experiment^:app.js            # app.js on the first commit parent
experiment@{2}:app.js         # app.js two commits ago

and so on.

schmijos adds in the comments:

you also can do this from a stash:

git checkout stash -- app.js

This is very useful if you're working on two branches and don't want to commit.

Lucas
  • 456
  • 2
  • 11
  • 15
VonC
  • 1,129,465
  • 480
  • 4,036
  • 4,755
  • 18
    One note: you will only get the most recent state of app.js, you will not get any history carried over from the experiment branch. – Frosty Mar 02 '10 at 16:18
  • So I can't import a file from master to another branch, only from other branches to master. Thoughts? – ThomasReggi Jun 05 '14 at 21:06
  • 3
    @ThomasReggi you should be able to import (checkout) a file from any branch to any current branch. If you can't, that can be a good question to ask here, with specific details like the exact error message, and version of Git and OS used. – VonC Jun 05 '14 at 21:23
  • I got it to work, I wanted to import a file that I didn't pull down from github. Sorry @VonC! So it was just importing the same file. – ThomasReggi Jun 07 '14 at 18:11
  • 4
    In a sub-directory, you can also use `experiment:./app.js`. (You don't have to specify the full path.) I learned this thanks to the very helpful error message git gave me: "Did you mean 'mybranch:full/path/to/my/file.xsl' aka 'mybranch:./file.xsl'?" Yes, I did! I don't think I've ever been so delighted by a fatal error message. – Evan Lenz Jul 07 '15 at 22:18
  • @EvanLenz sounds great! What version of Git are you using? – VonC Jul 08 '15 at 05:53
  • @vehsakul the syntax is for a checkout of a file on *any* branch: `git checkout $REVISION -- $FILENAME`. `experiment@{yesterday}` means the version as of yesterday on the branch `experiment`, even if you are on `master` branch. – VonC Nov 21 '15 at 13:14
  • I see that the checkout file is immediately added to index after this operation (as in "Changes to be commited"). – Tomasz Gandor Aug 05 '16 at 10:34
  • 2
    @TomaszGandor Yes, I mention that in http://stackoverflow.com/a/21066489/6309, where git show would not modify the index, but git checkout does modify the index. – VonC Aug 05 '16 at 12:29
  • 1
    Why do you use `--`, I've done the same without it. Am I missing something ? – wviana Feb 09 '17 at 20:23
  • 1
    @wviana It is to separate options from arguments: http://stackoverflow.com/a/1192194/6309 – VonC Feb 09 '17 at 20:54
  • While on master I tried `git checkout some_branch -- my.file` but it gave me `fatal: invalid reference: some_branch`. Had to first do `git checkout some_branch`, then `git checkout master`, then `git checkout some_branch -- my.file` to only get that file from branch. – Lidia Mar 23 '17 at 23:46
  • @lid probably because you only had origin/some_branch. – VonC Mar 23 '17 at 23:47
  • @VonC Yes, origin/some_branch works. It also gets me the latest version of the file on the branch, which is what I wanted. Thanks! – Lidia Mar 24 '17 at 01:32
  • I'd like to mention here, that you also can do this from a stash: `git checkout stash -- app.js`. This is very useful if you're working on two branches and don't want to commit. – schmijos Nov 14 '18 at 12:16
  • @schmijos Thank you. I have included your comment in the answer for more visibility. – VonC Nov 14 '18 at 13:06
  • Is that just copying a file? What happens if we merge? – Terry Tan Feb 02 '19 at 02:57
  • @TerryTan "What happens if we merge?": nothing more (or less) than if you manually copied over the content of that file in your branch: if there is no further modification (for that file) in both branches, a merge will ignore said file. – VonC Feb 02 '19 at 10:52
  • @PhilipRego I would like to see that case illustrated in a new separate question: that way, I will know what to fix. – VonC May 20 '19 at 21:14
  • couldnt reproduce – Philip Rego May 20 '19 at 22:09
  • I found it. It should be covered in this answer. See that I get "invalid reference", but im able to fetch the branch. $ git checkout issue/2020.07.04 -- pom.xml fatal: invalid reference: issue/2020.07.04 $ git fetch origin issue/2020.07.04 From https://example.com * branch issue/2020.07.04 -> FETCH_HEAD – Philip Rego May 21 '19 at 19:14
  • @PhilipRego Interesting. For testing, I still think a separate question illustrating the bug in more details (with OS and Git version) would be useful. Once we all understand what is going wrong, I will edit this answer. – VonC May 21 '19 at 19:41
  • Stack doens't let me post questions anymore. git version 2.17.1.windows.2 Windows 7 – Philip Rego May 21 '19 at 19:47
  • @PhilipRego As I mentioned before, this would be better addressed as a new question. You might consider creating a new account just for that purpose (and request merging that new account later on) – VonC Jun 05 '19 at 18:17
  • See Dmitry Avtonomov's Answer. – Fried Brice Dec 05 '19 at 16:49
  • 1
    @FriedBrice See my answer: these days, it would be `git restore -s new-feature path/to/app.js` – VonC Dec 05 '19 at 17:00
  • What if I have to change the folder in which I want my code to be copied? – Pooja Sonkar Jun 10 '21 at 13:19
  • @PoojaSonkar I suppose you would need to restore first, then rename the folder. If I have misinterpreted your comment, please make it a new question, with a clear example. – VonC Jun 10 '21 at 14:43
511

Everything is much simpler, use git checkout for that.

Suppose you're on master branch, to get app.js from new-feature branch do:

git checkout new-feature path/to/app.js

// note that there is no leading slash in the path!

This will bring you the contents of the desired file. You can, as always, use part of sha1 instead of new-feature branch name to get the file as it was in that particular commit.

Note:new-feature needs to be a local branch, not a remote one.

dopexxx
  • 1,793
  • 17
  • 25
Dmitry Avtonomov
  • 7,729
  • 4
  • 30
  • 38
  • 106
    I find it helpful to always specify the origin `git checkout origin/source_branch path/to/file` because if you have neglected to update the source branch of your local repo, you might get an old version of the file...Ask me how I know. ;) – talyric May 15 '14 at 17:13
  • Should'nt we do `git checkout origin source_branch path/to/file` to get the branch on the remote? So it is VERY the last version of the file? See this link for difference between these two commands : http://stackoverflow.com/questions/26125162/difference-between-origin-branch-name-and-branch-name – Mymozaaa Feb 03 '16 at 18:15
  • 5
    @Mymozaaa the question did not mention remotes, thus the assumption that it is a purely local repo – Dmitry Avtonomov Feb 04 '16 at 20:10
  • 2
    Will this command bring the file's history, or just the last version of the file? – user1366265 May 10 '16 at 23:19
  • 2
    @user1366265 this command will put the file as it was in the particular commit you specify or the head of the branch you specify. There is no such a thing as "history of a file", all history information is only stored in branches. – Dmitry Avtonomov May 11 '16 at 17:09
  • @talyric - but if you haven't pulled or fetched, you'll be toast anyway. After fetch it's good to do a `git push . origin/otherbranch:otherbranch` anyway (update local branch without checking it out, but use only for fast-forward). – Tomasz Gandor Aug 05 '16 at 10:37
  • 4
    This seems to automatically stage the checked-out file. Is it possible to do the same without staging? – bluenote10 Nov 14 '17 at 10:02
  • `git fetch` before checkout – majurageerthan Apr 17 '20 at 04:13
79
git checkout branch_name file_name

Example:

git checkout master App.java

This will not work if your branch name has a period in it.

git checkout "fix.june" alive.html
error: pathspec 'fix.june' did not match any file(s) known to git.
Philip Rego
  • 460
  • 4
  • 19
  • 31
Sarath
  • 855
  • 7
  • 4
  • @PhilipRego This answer is correct. I'm guessing there is different capitalization or punctuation in your branch, or you only have a remote branch and not a local one. See the git checkout doc: https://git-scm.com/docs/git-checkout#Documentation/git-checkout.txt-emgitcheckoutemlttree-ishgt--ltpathspecgt82308203 – Bret Jun 12 '19 at 14:14
  • @Bret I found it doesn't work when the branch name has a period. I suggested an edit – Philip Rego Jun 12 '19 at 17:39
55

Supplemental to VonC's and chhh's answers:

git show experiment:path/to/relative/app.js > app.js

# If your current working directory is relative, then just use:
git show experiment:app.js > app.js

or

git checkout experiment -- app.js
Audwin Oyong
  • 2,061
  • 3
  • 10
  • 31
AlexLordThorsen
  • 7,354
  • 3
  • 42
  • 93
  • 2
    Cool! I hate specifying long paths. Is the double dash (`--`) between the branch name and paths optional? Is it only to prevent paths, which would start with a dash, from being treated as options / switches? – Tomasz Gandor Aug 05 '16 at 10:40
  • Honestly I don't know. I didn't even notice that I had forgotten the double dash until you pointed this out. – AlexLordThorsen Aug 05 '16 at 21:28
  • 8
    @TomaszGandor The `--` is optional, but it's more useful to avoid conflict with branch names. For example, `git checkout -- foo` means "check out file foo from HEAD" (ie. overwrite local changes in *foo*, ie. a subset of `git reset --hard`), but `git checkout foo` could mean that *or* "let's go to branch *foo*". – Alois Mahdal Feb 23 '18 at 18:43
47

All about checking out files or directories in git

1. How to check out one or more files or directories from another branch or commit hash into your currently-checked-out branch:

# check out all files in <paths> from branch <branch_name>
git checkout <branch_name> -- <paths>

Source: http://nicolasgallagher.com/git-checkout-specific-files-from-another-branch/.

See also man git checkout.

Examples:

# Check out "somefile.c" from branch `my_branch`
git checkout my_branch -- somefile.c

# Check out these 4 files from `my_branch`
git checkout my_branch -- file1.h file1.cpp mydir/file2.h mydir/file2.cpp

# Check out ALL files from my_branch which are in
# directory "path/to/dir"
git checkout my_branch -- path/to/dir

If you don't specify, the branch_name it is automatically assumed to be HEAD, which is your most-recent commit of the currently-checked-out branch. So, you can also just do this to check out "somefile.c" and have it overwrite any local, uncommitted changes:

# Check out "somefile.c" from `HEAD`, to overwrite any local, uncommitted
# changes
git checkout -- somefile.c

# Or check out a whole folder from `HEAD`:
git checkout -- some_directory

2. Going Further: How to check out any file from any branch or commit hash into any location on your computer (VERY USEFUL!):

# General form
git show my_branch_or_commit_hash:my_file.cpp > any/path/my_file.cpp

# Example: check out `main.cpp` from 3 commits ago in your currently-checked-out
# branch (3 commits prior to `HEAD`, or `HEAD~3`) into a temporary directory
mkdir ../temp
git show HEAD~3:main.cpp > ../temp/main_old.cpp

Source where I learned this: @Jakub Narębski's answer to: git-checkout older revision of a file under a new name

3. What if you're in the middle of resolving git merge, git cherry-pick, git rebase, or git revert changes?

Well, in that case, you better do the following. Note: to know which commit hash or branch --theirs and --ours are in each context, see my answer here: Who is "us" and who is "them" according to Git?:

# Keep `--theirs` for all conflicts within this file
git checkout --theirs -- path/to/some/file
# OR: keep `--ours` for all conflicts within this file
git checkout --ours -- path/to/some/file

OR:

# Keep `--theirs` for all conflicts within files inside this dir
git checkout --theirs -- path/to/some/dir
# OR: keep `--ours` for all conflicts within files inside this dir
git checkout --ours -- path/to/some/dir

Do NOT do the regular checkout form in the previous section before this, unless that's what you really want to do. See the "WARNING WARNING WARNING" section in my answer referenced above: Who is "us" and who is "them" according to Git?.

DEALING WITH path does not have our version or path does not have their version ERRORS:

If you ever see errors like this:

error: path 'path/to/some/dir/file1.cpp' does not have our version
# OR
error: path 'path/to/some/dir/file1.cpp' does not have their version

...when running the commands above, then you simply need to git rm those files first and then try the git checkout --ours or git checkout --theirs command again. See my answer here for a detailed explanation of these commands, including a form to automatically find and delete those errored files for you: git checkout --ours when file spec includes deleted file.

4. What if you want to reset a certain file or directory to exactly match that file or directory's state in another commit or branch?

In this case, git checkout my_branch -- some_file_or_dir is NOT enough, because if you have files in the specified directory which exist in your currently-checked-out branch or commit but do NOT exist in my_branch, then you'd like them to be deleted locally, but git checkout does NOT delete any files which exist locally but not on the specified commit, rather, it only overwrites files locally with their versions from the specified commit. So, to also delete files locally which should not be there, so that what you end up with locally is an exact copy of what you have on commit or branch my_branch, you must do the following:

# How to "hard reset" "path/to/some/file_or_dir" to its state exactly as it was
# at commit or branch `my_branch`
#
# WARNING: `git status` should be TOTALLY CLEAN before beginning this process!
# Otherwise, you risk PERMANENTLY LOSING any uncommitted changes shown by 
# `git status`, since `git clean -fd` 'f'orce deletes ALL files
# and 'd'irectories which are in your current working tree (file system), but
# which are *not* in the path you specify below in commit or branch `my_branch`.
# Therefore, anything NOT already committed gets **permanently lost** as though
# you had used `rm` on it!

git reset my_branch -- path/to/some/file_or_dir
git checkout-index -fa
git clean -fd  # SEE WARNING ABOVE!
git commit -m "hard reset path/to/some/file_or_dir to its state \
as it was at my_branch"

See my own answer here for more details on this: Why git can't do hard/soft resets by path?

See also:

  1. Quick links to my answers I reference frequently and consider to be "git fundamentals":
    1. Various ways to create a branch in git from another branch
    2. All about checking out files or directories in git
    3. Who is "us" and who is "them" according to Git?
  2. I show some more of these examples of git checkout in my answer here: Who is "us" and who is "them" according to Git?.
  3. [my answer on "How to do a --soft or --hard git reset by path"] Why git can't do hard/soft resets by path?
  4. git-checkout older revision of a file under a new name
  5. [my answer] git checkout --ours when file spec includes deleted file
  6. [my answer] Using git, how do you reset the working tree (local file system state) to the state of the index ("staged" files)?
Gabriel Staples
  • 22,024
  • 5
  • 133
  • 166
  • WARNING!! Never ever do `git clean -fd` without first understanding what it will do. Mercifully Jetbrains kept backups of these files for me. Think, `\rm -rf *`... – jtlz2 May 20 '22 at 12:30
  • 1
    @jtlz2, I added a long WARNING block in a comment above that code. Does that cover it? – Gabriel Staples May 20 '22 at 19:14
20

To restore a file from another branch, simply use the following command from your working branch:

git restore -s my-other-branch -- ./path/to/file

The -s flag is short for source i.e. the branch from where you want to pull the file.

(The chosen answer is very informative but also a bit overwhelming.)

vinzee
  • 17,022
  • 14
  • 42
  • 60
Conner Smith
  • 303
  • 3
  • 7
8

Or if you want all the files from another branch:

git checkout <branch name> -- .
Jester
  • 2,642
  • 21
  • 20
  • 29
    The initial queston contains "just one file". – greatvovan Jul 11 '17 at 17:40
  • 1
    this replaces existing files rather than merging – Amare Sep 12 '18 at 23:44
  • 3
    This `.` makes a huge difference: instead of moving to another branch it copies all files from there while still leaving you on the current one. You get contents from other branch without going into it. – Xeverous Sep 20 '18 at 09:51
  • Why -1: first. this is an answer, but not to the question asked. Second, this overwriting all files in the current directory and all subdirectories unconditionally. Perhaps you shouldn't assume that the OP is a Git pro. Many people, in my experience, treat Git command like magic spells, and this form of the command is really dangerous. IMO, if you also allow me an advice not asked for, you'll make the community a better service by removing your answer. – kkm Feb 26 '21 at 11:35
4

Review the file on github and pull it from there

This is a pragmatic approach which doesn't directly answer the OP, but some have found useful:

If the branch in question is on GitHub, then you can navigate to the desired branch and file using any of the many tools that GitHub offers, then click 'Raw' to view the plain text, and (optionally) copy and paste the text as desired.

I like this approach because it lets you look at the remote file in its entirety before pulling it to your local machine.

fearless_fool
  • 31,575
  • 23
  • 126
  • 205
  • 2
    However copy and pasting the raw file is likely to cause unwanted character changes in your git diff. It's safer to save the file directly to your project to ensure no changes. – Philip Rego Jun 05 '19 at 18:21
3
git checkout <branch_name> -- <paths>

More info

Pravin
  • 1,107
  • 11
  • 20
2

If you want the file from a particular commit (any branch), say 06f8251f

git checkout 06f8251f path_to_file

For example, on Windows:

git checkout 06f8251f C:\A\B\C\D\file.h
vinzee
  • 17,022
  • 14
  • 42
  • 60
arupjbasu
  • 171
  • 4
  • 1
    Thanks for taking the time to answer! But this does not answer the question, and a good answer that is very detailled has already been posted 9 years ago. There is no need to bump the question. – Turtle Jul 25 '19 at 09:35
  • 3
    This is a valid practical scenario . The answer deals correctly with the branch , but what about looking at a particular commit of the branch . – arupjbasu Jul 25 '19 at 09:58
2

Another way is to create a patch with the differences and apply it in the master branch For instance. Let's say the last commit before you started working on app.js is 00000aaaaa and the commit containg the version you want is 00000bbbbb

The you run this on the experiment branch:

git diff 00000aaaaa 00000bbbbb app.js > ~/app_changes.git

This will create a file with all the differences between those two commits for app.js that you can apply wherever you want. You can keep that file anywhere outside the project

Then, in master you just run:

git apply ~/app_changes.git

now you are gonna see the changes in the projects as if you had made them manually.

Santi
  • 1,472
  • 1
  • 12
  • 12
2

There is also a simple solution for all who like to avoid unknown git commands or are afraid to wreck something:

  1. check out to the branch that the file is in
  2. copy that file to somewhere else on your computer
  3. check out to the branch the file needs to get to
  4. paste the file in place

probably takes longer than the appropriate git command... but it works and is easy to understand

CHH
  • 59
  • 1
  • 6
1

To checkout a file from another branch is a simple one line command:

git checkout branch C:\path\to\file.cs

If you'd like multiple files

git checkout branch C:\path\to\file1.cs C:\path\to\file2.cs
Kellen Stuart
  • 6,353
  • 5
  • 50
  • 73
-3
git checkout master               -go to the master branch first
git checkout <your-branch> -- <your-file> --copy your file data from your branch.

git show <your-branch>:path/to/<your-file> 

Hope this will help you. Please let me know If you have any query.

Rohit Saini
  • 449
  • 5
  • 11