590

How do I checkout just one file from a git repo?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284
  • 10
    What do you mean by check out? Obtain a copy of only one file from a remote repository? – Cascabel Mar 17 '10 at 23:59
  • 2
    If the repo in question is using gitweb you could just download the file directly from there. As I'm trying to explain below, what you're asking isn't really a standard git operation. – Cascabel Mar 18 '10 at 00:08
  • 2
    possible duplicate of [How do I revert one file to the last commit in git?](http://stackoverflow.com/questions/692246/how-do-i-revert-one-file-to-the-last-commit-in-git) – nawfal Feb 24 '13 at 20:50
  • You can use chrome extension [GitHub Mate](https://chrome.google.com/webstore/detail/github-mate/baggcehellihkglakjnmnhpnjmkbmpkf), enables you click the file icon to download it. – Cam Song Dec 18 '13 at 05:31
  • Possible duplicate of [Retrieve a single file from a repository](http://stackoverflow.com/questions/1125476/retrieve-a-single-file-from-a-repository) – Jacek Krysztofik Dec 31 '16 at 03:46
  • **See instead:** https://stackoverflow.com/a/600189/42223 – dreftymac Sep 13 '19 at 23:06
  • I've created a ``bash`` function which avoids downloading the history, which retrieves a single branch and which retrieves a list of files or directories you need. See it here: https://stackoverflow.com/questions/60190759/how-do-i-clone-fetch-or-sparse-checkout-a-single-directory-or-a-list-of-directo – Richard Gomes Feb 12 '20 at 14:41
  • Related: people landing here from Google searches may be looking for this instead, even though it's a completely different question altogether: [How to get just one file from another branch](https://stackoverflow.com/q/2364147/4561887). – Gabriel Staples Mar 09 '21 at 23:44
  • not a git command but checkout/download one file. Try `svn export --force https://github.com/{USER}/{REPO}/trunk/{PATH}/{TO}/{FILE} {PATH}/{TO}/{CHECKOUT`} [`--force` to overwrite the target/downloaded file] – Robert Ranjan Nov 10 '22 at 23:23

27 Answers27

275

Originally, I mentioned in 2012 git archive (see Jared Forsyth's answer and Robert Knight's answer), since git1.7.9.5 (March 2012), Paul Brannan's answer:

git archive --format=tar --remote=origin HEAD:path/to/directory -- filename | tar -O -xf -

But: in 2013, that was no longer possible for remote https://github.com URLs.
See the old page "Can I archive a repository?"

The current (2018) page "About archiving content and data on GitHub" recommends using third-party services like GHTorrent or GH Archive.


So you can also deal with local copies/clone:

You could alternatively do the following if you have a local copy of the bare repository as mentioned in this answer,

git --no-pager --git-dir /path/to/bar/repo.git show branch:path/to/file >file

Or you must clone first the repo, meaning you get the full history:

  • in the .git repo

  • in the working tree.

  • But then you can do a sparse checkout (if you are using Git1.7+),:

    • enable the sparse checkout option (git config core.sparsecheckout true)
    • adding what you want to see in the .git/info/sparse-checkout file
    • re-reading the working tree to only display what you need

To re-read the working tree:

$ git read-tree -m -u HEAD

That way, you end up with a working tree including precisely what you want (even if it is only one file)


Richard Gomes points (in the comments) to "How do I clone, fetch or sparse checkout a single directory or a list of directories from git repository?"

A bash function which avoids downloading the history, which retrieves a single branch and which retrieves a list of files or directories you need.


With Git 2.40 (Q1 2023), the logic to see if we are using the "cone" mode by checking the sparsity patterns has been tightened to avoid mistaking a pattern that names a single file as specifying a cone.

See commit 5842710 (03 Jan 2023) by William Sprent (williams-unity).
(Merged by Junio C Hamano -- gitster -- in commit ab85a7d, 16 Jan 2023)

dir: check for single file cone patterns

Signed-off-by: William Sprent
Acked-by: Victoria Dye

The sparse checkout documentation states that the cone mode pattern set is limited to patterns that either recursively include directories or patterns that match all files in a directory.
In the sparse checkout file, the former manifest in the form:

/A/B/C/

while the latter become a pair of patterns either in the form:

/A/B/
!/A/B/*/

or in the special case of matching the toplevel files:

/*
!/*/

The 'add_pattern_to_hashsets()' function contains checks which serve to disable cone-mode when non-cone patterns are encountered.
However, these do not catch when the pattern list attempts to match a single file or directory, e.g. a pattern in the form:

/A/B/C

This causes sparse-checkout to exhibit unexpected behaviour when such a pattern is in the sparse-checkout file and cone mode is enabled.

Concretely, with the pattern like the above, sparse-checkout, in non-cone mode, will only include the directory or file located at '/A/B/C'.
However, with cone mode enabled, sparse-checkout will instead just manifest the toplevel files but not any file located at '/A/B/C'.

Relatedly, issues occur when supplying the same kind of filter when partial cloning with '--filter=sparse:oid=<oid>'.
'upload-pack' will correctly just include the objects that match the non-cone pattern matching.
Which means that checking out the newly cloned repo with the same filter, but with cone mode enabled, fails due to missing objects.

To fix these issues, add a cone mode pattern check that asserts that every pattern is either a directory match or the pattern '/*'.
Add a test to verify the new pattern check and modify another to reflect that non-directory patterns are caught earlier.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • can you commit the changes in the sparse checkout? – Tilo Jan 11 '12 at 06:10
  • 2
    @Tilo: not sure, but it should be possible, considering the clone has been a full one. – VonC Jan 11 '12 at 07:02
  • 3
    How's this better than "git checkout HASH path-to-file" as noted in other answers? was that just not available at the time? – 0x6A75616E Aug 30 '12 at 17:47
  • 2
    @juand the idea was to not have to load the all working tree before doing git checkout. – VonC Aug 30 '12 at 18:04
  • 2
    btw we can use `git archive` now. – Jared Forsyth Sep 10 '13 at 07:14
  • @JaredForsyth Great! And +1 to your answer. I have reference it in mine for more visibility. – VonC Sep 10 '13 at 07:24
  • Notice that for `git archive` to work, you MUST first run this inside the directory of your repository on your git server (where git daemon runs): `git config daemon.uploadarch true`. credit: @patthoyts (http://stackoverflow.com/a/1126333/2591231) – Doron Gold Nov 08 '14 at 15:40
  • @DoronGold Good point. I have included your comment in the answer for more visibility. – VonC Nov 08 '14 at 16:45
  • @purpletech because the emphasis with Git is on the repository, a coherent set of files where *one* file is not supposed to make sense without the others. This differs from sparse checkout, which allows you to get only a part of a repo: http://stackoverflow.com/a/13738951/6309 and http://stackoverflow.com/a/26129796/6309 – VonC Jun 18 '15 at 22:06
  • deleted a file from working directory but want to restore it form the repo, how does that above command work? – Si8 Nov 24 '17 at 19:57
  • @Si8 it doesn't. You would simply do a `git checkout -- myDeletedFile`. – VonC Nov 24 '17 at 20:37
  • @VonC Thank you. I was able to follow the documentation (Ahhh the wonder of it). I appreciate your respectful response. – Si8 Nov 27 '17 at 16:41
  • Is this answer still relevant? I am getting a 'The remote end hung up unexpectedly' message...( see https://stackoverflow.com/questions/30659758/git-archive-remote-end-hung-up) – zwep Oct 11 '18 at 13:57
  • @zwep Agreed. `git archive` alone would no longer work for remote servers like github.com. I have rewritten the answer accordingly. – VonC Oct 11 '18 at 15:55
  • @VonC Ah I see now.. sorry, must have missed that part yesterday. – zwep Oct 12 '18 at 10:23
  • I've created a ``bash`` function which avoids downloading the history, which retrieves a single branch and which retrieves a list of files or directories you need. See it here: https://stackoverflow.com/questions/60190759/how-do-i-clone-fetch-or-sparse-checkout-a-single-directory-or-a-list-of-directo – Richard Gomes Feb 12 '20 at 14:42
  • 1
    This `git show` command for obtaining file content from a bare repo is EXACTLY what I was looking for. Thank you! – Gio Jul 19 '20 at 16:46
258

First clone the repo with the -n option, which suppresses the default checkout of all files, and the --depth 1 option, which means it only gets the most recent revision of each file

git clone -n git://path/to/the_repo.git --depth 1

Then check out just the file you want like so:

cd the_repo
git checkout HEAD name_of_file
Nick Moore
  • 15,547
  • 6
  • 61
  • 83
  • 12
    While literally this does check out a single file, it's almost certainly not what the OP wants to do, since they will have all of the files (and the checkout is a no-op anyway). – Cascabel Mar 17 '10 at 23:58
  • 5
    I don't think this even works - with `-n` the work tree and index end up in sync. That is, all content shows up as deleted. You have to either `git reset HEAD` or `git checkout HEAD file`. It's also really difficult to work with the repository at this point unless you really understand how git works. – Cascabel Mar 18 '10 at 00:06
  • Yes, you are quite right. I gave the answer before I tried it myself. I was going to delete it, but with your useful additions I shall leave it now. – Nick Moore Mar 18 '10 at 00:14
  • All right, so with Debilski's addition, you can definitely do this, only fetching enough data to construct... the entire work tree in its current state. I think stefanB is probably closest to what the OP actually needs to know, namely, how to make changes to a single file with git. – Cascabel Mar 18 '10 at 00:52
  • 1
    Getting a single file from the repo was something I needed for a particular build process. This answer came up on a target search ... it might not have been what OP wanted but +1 from me :) – Daniel Elliott Jun 16 '11 at 06:10
  • 3
    And if the OP and OOPs like DanielElliott really just want the file (not the repo) adding another `rm -rf .git` to NickMoore's script would clean up all traces of the cloned repo and perhaps allay Jefromi's concern about having a hard-to-use repo laying around. Makes it very useful for me for several applications, like my challenge today to build a post-receive hook to update the version of another post-receive hook automagicaly. – hobs Aug 10 '12 at 00:56
  • 9
    This is a much better answer than the accepted. Glad I kept reading. – Eric Uldall Oct 02 '14 at 21:51
  • 7
    **This answer is the best** (but `git` is not the best for this kind of work). This answer is also valid for [this question](http://stackoverflow.com/q/11834386/287948), or [this other popular one](http://stackoverflow.com/q/600079/287948), and many other ones: change `name_of_file` to `name_of_folder`. Git in nowadays (2014s) offer [submodules](http://git-scm.com/book/en/v2/Git-Tools-Submodules) to repo-owner offer some por friendly for repo-users. – Peter Krauss Nov 01 '14 at 12:13
  • 1
    I agree: for its conciseness and strict adherence to the OP this is the best answer. – rgulia Jun 01 '16 at 15:02
  • you can run `git ls-files -m` or `git status | grep modified` to only show modified fields – baligena Jul 08 '16 at 19:08
  • 1
    THIS SHOULD BE THE ACCEPTED ANSWER! – emeraldhieu Sep 01 '19 at 11:14
  • I've created a ``bash`` function which avoids downloading the history, which retrieves a single branch and which retrieves a list of files or directories you need. See it here: https://stackoverflow.com/questions/60190759/how-do-i-clone-fetch-or-sparse-checkout-a-single-directory-or-a-list-of-directo – Richard Gomes Feb 12 '20 at 14:43
  • I used this solution because I wanted to be able to trigger a build of a repository in our Ci/CD system by updating a single file and committing it back. I tested it out on our SCRATCH repository first. It worked, I was able to check out a single file and update it. Only snag was, when I committed the single file change, git assumed that I wanted to delete everything else. Since this was our scratch repo I let it go ahead and indeed it did destroy the entire repository's contents! – Paul M Mar 25 '20 at 12:11
  • the secret is to do a "git reset HEAD ." ; thus : mkdir SCRATCH ; cd SCRATCH ; git clone -n "ssh://git.example.com/SCRATCH" --depth 1 . ; git reset HEAD . ; date > .trigger_file ; git add .trigger_file ; git commit -m "NOBUG triggering pipeline" ; git push ; – Paul M Mar 25 '20 at 14:24
  • This is also almost the answer I had deduced myself. However I didn't manage to get the folder I wanted actually checked out; not even `git restore --staged` worked despite what `git status` claims. I tried specifying the branch from which to checkout, I'd never have thought to add `HEAD`! – RJVB Aug 12 '23 at 11:10
118

If you already have a copy of the git repo, you can always checkout a version of a file using a git log to find out the hash-id (for example 3cdc61015724f9965575ba954c8cd4232c8b42e4) and then you simply type:

git checkout hash-id path-to-file

Here is an actual example:

git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /var/www/css/page.css
techexpert
  • 2,444
  • 3
  • 20
  • 21
98

Normally it's not possible to download just one file from git without downloading the whole repository as suggested in the first answer. It's because Git doesn't store files as you think (as CVS/SVN do), but it generates them based on the entire history of the project.

But there are some workarounds for specific cases. Examples below with placeholders for user, project, branch, filename.

GitHub

wget https://raw.githubusercontent.com/user/project/branch/filename

GitLab

wget https://gitlab.com/user/project/raw/branch/filename

GitWeb

If you're using Git on the Server - GitWeb, then you may try in example (change it into the right path):

wget "http://example.com/gitweb/?p=example;a=blob_plain;f=README.txt;hb=HEAD"

GitWeb at drupalcode.org

Example:

wget "http://drupalcode.org/project/ads.git/blob_plain/refs/heads/master:/README.md"

googlesource.com

There is an undocumented feature that allows you to download base64-encoded versions of raw files:

curl "https://chromium.googlesource.com/chromium/src/net/+/master/http/transport_security_state_static.json?format=TEXT" | base64 --decode

In other cases check if your Git repository is using any web interfaces.

If it's not using any web interface, you may consider to push your code to external services such as GitHub, Bitbucket, etc. and use it as a mirror.

If you don't have wget installed, try curl -O (url) alternatively.

Carolus
  • 477
  • 4
  • 16
kenorb
  • 155,785
  • 88
  • 678
  • 743
  • 6
    And if I don't use github ? – Zulu Jul 12 '13 at 07:28
  • 87
    Then don't use this method. – Alan Mar 04 '14 at 12:43
  • 8
    I would argue against the statement that git "generates [files] based on the entire history of the project". It is more correct to say that git stores snapshots of the states of files in the form of hash trees. Certainly there is no generating going on. – Jay Sullivan Feb 07 '16 at 03:00
  • 3
    This answer was most useful to me since I was trying to simply restore a file that I'd intentionally deleted locally along with several others (without committing the delete) but later decided it was needed while the others still weren't – rshdev Feb 20 '16 at 14:41
  • Call me insane, but I just make daily backups. Then, if I want an old file, I can go and get it. Incredibly, this even works with files in other projects!!!!!!!! – Geoff Kendall Oct 20 '16 at 15:36
  • This was actually a perfect answer for what I needed. No branching, check outs, or anything. – DNorthrup Dec 23 '16 at 18:34
  • 14
    You know that sinking feeling when you want to do something simple with Git, come on SO to see how it's done, and halfway through the answer your brain stops and everything becomes fuzzy and sad. Then you scroll down and find this brilliant `wget` answer and simplicity returns, along with happiness. Thanks man. – pgr Apr 09 '17 at 14:22
  • 1
    This is a great answer because it addresses a problem that a lot of users, including myself, struggle with. That we think we know how we want to do something, but actually our entire methodology is wrong. I know people get flak for Q&As like **Q:"How do I do this with this"** and **A:"You shouldn't. Use this instead"**. But sometimes that's the best answer. As it was for me in this case. – Stack of Pancakes May 13 '18 at 13:31
  • 1
    I like this answer because git archive is not supported by the gradle git library and I needed to pull one file from a different repo. I used the rest api of bitbucket with a personal access token. https://docs.atlassian.com/bitbucket-server/rest/5.12.0/bitbucket-rest.html?utm_source=%2Fstatic%2Frest%2Fbitbucket-server%2Flatest%2Fbitbucket-rest.html&utm_medium=301 – Fresh Codemonger Jul 23 '18 at 19:38
52

Minimal Guide

git checkout -- <filename>


Ref: https://git-scm.com/docs/git-checkout

Dup: Undo working copy modifications of one file in Git?

Community
  • 1
  • 1
Geoffrey Hale
  • 10,597
  • 5
  • 44
  • 45
  • For further explanation.[broc.seib](https://stackoverflow.com/a/29762249/1278112)'s answer explained what is the relevant part of the man page for `git-checkout`. – Shihe Zhang Jun 29 '18 at 03:51
45

git checkout branch_or_version -- path/file

example: git checkout HEAD -- main.c

Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • I really got confused by other answers. this did job for me. before updating i deleted the file to be replaced. then did this: ```git checkout HEAD abcd.cpp``` – veenus adiyodi Oct 29 '20 at 13:26
43

Now we can! As this is the first result on google, I thought I'd update this to the latest standing. With the advent of git 1.7.9.5, we have the git archive command which will allow you to retrieve a single file from a remote host.

git archive --remote=git://git.foo.com/project.git HEAD:path/in/repo filename | tar -x

See answer in full here https://stackoverflow.com/a/5324532/290784

Raphael
  • 9,779
  • 5
  • 63
  • 94
Jared Forsyth
  • 12,808
  • 7
  • 45
  • 54
  • @Benubird it is the hostname of your repo. For github (if github supported the archive command, which last I checked it doesn't), it would be `github.com` – Jared Forsyth May 14 '15 at 15:11
  • 1
    This worked for me, but only if I specified the branch (or refname) alone, e.g. just `HEAD` or `master` not `HEAD:directory`. – stormbeta Apr 04 '16 at 22:11
  • 6
    This worked for me on bitbucket: ```git archive --remote=git@bitbucket.org:user/repo branch:path/to file | tar -x``` – Dave Jan 23 '19 at 18:33
26

Here is the complete solution for pulling and pushing only a particular file inside git repository:

  1. First you need to clone git repository with a special hint –no checkout
git clone --no-checkout <git url>
  1. The next step is to get rid of unstaged files in the index with the command:
git reset
  1. Now you are allowed to start pulling files you want to change with the command:
git checkout origin/master <path to file>
  1. Now the repository folder contains files that you may start editing right away. After editing you need to execute plain and familar sequence of commands.
git add <path to file>
git commit -m <message text>
git push
the one
  • 437
  • 4
  • 7
  • 1
    This. It answers the question with a simple to understand and remember workflow. Also, turns out you don't need the `origin/master` in the checkout: a simple `git checkout ` works for step 3. – John Jul 22 '20 at 14:50
  • 2
    git reset is a bit dangerous here as it will mark the files to be deleted as an Undo procedure. And the 'git commit ...' and 'git push...' could also commit the deletions.. May remove lots of files from the repository. 'git commit YOUR_FILE -m ' should be the correct thing... – Farrukh Waheed Aug 04 '21 at 13:12
  • 1
    I just tried to use this command set and it seems it is the most dangerous/wrong answer. First command actually brings entire tree, but does not show anything on running "ls" command. When you run second command, you actually see that all files have gone in deleted mode and staged as well. Now, if you do a git add of your updated file, it will actually remove others and keep this single file. Just to try, I went to third step and tried committing file, which actually resulted in renaming of another file by my present file, which again is completely wrong. – rkdove96 May 27 '22 at 11:43
24

Working in GIT 1.7.2.2

For example you have a remote some_remote with branches branch1, branch32

so to checkout a specific file you call this commands:

git checkout remote/branch path/to/file

as an example it will be something like this

git checkout some_remote/branch32 conf/en/myscript.conf
git checkout some_remote/branch1 conf/fr/load.wav

This checkout command will copy the whole file structure conf/en and conf/fr into the current directory where you call these commands (of course I assume you ran git init at some point before)

anvk
  • 1,183
  • 8
  • 10
20

git clone --filter from Git 2.19 actually skips downloading extra files

This option will actually skip fetching most unneeded objects from the server. E.g. to obtain just the file small/0000 from this test repository: https://github.com/cirosantilli/test-git-partial-clone-big-small-no-bigtree we can do:

git clone --depth 1 --no-checkout --filter=blob:none \
  https://github.com/cirosantilli/test-git-partial-clone-big-small-no-bigtree
cd test-git-partial-clone-big-small-no-bigtree
git checkout master -- small/0000

It also works with multiple files:

git checkout master -- small/0000 small/0001

but note that files are downloaded one by one, so it will be very slow if you do that for a huge number of files. Entire directories can however be efficiently downloaded as per: How do I clone a subdirectory only of a Git repository?

That test repository is designed with to have several large files, and download is basically instantaneous, so we can be sure that we are not downloading those large files at all.

The format of --filter is documented on man git-rev-list. An extension was made to the Git remote protocol to support this feature.

Tested on Git 2.37.2, Ubuntu 22.10.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
  • 2
    Nice, I must have missed that option. +1 – VonC Sep 12 '18 at 09:01
  • This does not work with git 2.39. When using `--depth 1 --no-checkout --filter=blob:none` all files are left in a deleted/staged state. You need to run `git reset` first, like mentioned above https://stackoverflow.com/a/54968394/321013 – Martin Ba May 04 '23 at 08:16
  • @MartinBa what is the use case? Why does it matter that the files are in staged state? Do you want to modify commit and push back? – Ciro Santilli OurBigBook.com May 04 '23 at 10:31
  • @Ciro ... The `git checkout` command simply fails to create the file with an error because it is staged deleted. Your command sequence does not work at all without the added reset. – Martin Ba May 05 '23 at 11:59
  • @MartinBa hmmm I don't reproduce on Git 2.39.3 built from source, Ubuntu 22.10. The file was present. Let me know if you figure something out related to the version issue. – Ciro Santilli OurBigBook.com May 05 '23 at 13:14
16

Very simple:

git checkout from-branch-name -- path/to/the/file/you/want

This will not checkout the from-branch-name branch. You will stay on whatever branch you are on, and only that single file will be checked out from the specified branch.

Here's the relevant part of the manpage for git-checkout

git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>...
       When <paths> or --patch are given, git checkout does not switch
       branches. It updates the named paths in the working tree from the
       index file or from a named <tree-ish> (most often a commit). In
       this case, the -b and --track options are meaningless and giving
       either of them results in an error. The <tree-ish> argument can be
       used to specify a specific tree-ish (i.e. commit, tag or tree) to
       update the index for the given paths before updating the working
       tree.

Hat tip to Ariejan de Vroom who taught me this from this blog post.

broc.seib
  • 21,643
  • 8
  • 63
  • 62
8

Two variants on what's already been given:

git archive --format=tar --remote=git://git.foo.com/project.git HEAD:path/to/directory filename | tar -O -xf -

and:

git archive --format=zip --remote=git://git.foo.com/project.git HEAD:path/to/directory filename | funzip

These write the file to standard output.

Paul Brannan
  • 1,625
  • 20
  • 20
8

You can do it by

git archive --format=tar --remote=origin HEAD | tar xf -
git archive --format=tar --remote=origin HEAD <file> | tar xf -
Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
7

Say the file name is 123.txt, this works for me:

git checkout --theirs  123.txt

If the file is inside a directory A, make sure to specify it correctly:

git checkout --theirs  "A/123.txt"
Ruturaj Bisure
  • 151
  • 1
  • 13
Joseph Wu
  • 4,786
  • 1
  • 21
  • 19
4

In git you do not 'checkout' files before you update them - it seems like this is what you are after.

Many systems like clearcase, csv and so on require you to 'checkout' a file before you can make changes to it. Git does not require this. You clone a repository and then make changes in your local copy of repository.

Once you updated files you can do:

git status

To see what files have been modified. You add the ones you want to commit to index first with (index is like a list to be checked in):

git add .

or

git add blah.c

Then do git status will show you which files were modified and which are in index ready to be commited or checked in.

To commit files to your copy of repository do:

git commit -a -m "commit message here"

See git website for links to manuals and guides.

stefanB
  • 77,323
  • 27
  • 116
  • 141
  • 1
    And if your goal is to patch this single file and submit it back, you'll need to either push (but probably you don't have push access for this project?) or use `git format-patch` to create a patch for submission (`git format-patch -1` will create a patch for just your most recent commit). – Cascabel Mar 18 '10 at 00:58
  • Thanks, that was a good explanation coming to Git from Clearcase – Kellen Stuart Aug 10 '18 at 16:44
3

If you need a specific file from a specific branch from a remote Git repository the command is:

git archive --remote=git://git.example.com/project.git refs/heads/mybranch path/to/myfile |tar xf -

The rest can be derived from @VonC's answer:

If you need a specific file from the master branch it is:

git archive --remote=git://git.example.com/project.git HEAD path/to/myfile |tar xf -

If you need a specific file from a tag it is:

git archive --remote=git://git.example.com/project.git mytag path/to/myfile |tar xf -
Alex Harvey
  • 14,494
  • 5
  • 61
  • 97
  • Mother Corp. decided that automated HTTP/S access is now verboten! This technique allows me to automate getting a single file from a repository without checking out the Whole Thing. Thank you and kudos! – JS. Feb 28 '19 at 18:19
3

this works for me. use git with some shell command

git clone --no-checkout --depth 1 git.example.com/project.git && cd project && git show HEAD:path/to/file_you_need > ../file_you_need && cd .. && rm -rf project
ahprosim
  • 308
  • 1
  • 5
  • 1
    Please put the code in proper format like `git clone --no-checkout --depth 1 git.example.com/project.git && cd project && git show HEAD:path/to/file_you_need > ../file_you_need && cd .. && rm -rf project`, try using Ctrl+K whenever putting codes. – Vicky Dev Jul 28 '22 at 12:22
2

Another solution, similar to the one using --filter=blob:none is to use --filter=tree:0 (you can read an explanation about the differences here).

This method is usually faster than the blob-one because it doesn't download the tree structure, but has a drawback. Given you are delaying the retrieval of the tree, you will have a penalty when you enter into the repo directory (depending on the size and structure of your repo it may be many times larger compared with a simple shallow-clone).

If that's the case for you, you can fix it by not entering into the repo:

git clone -n --filter=tree:0 <repo_url> tgt_dir
git -C tgt_dir checkout <branch> -- <filename>
cat tgt_dir/<filename> # or move it to another place and delete tgt_dir ;)

Take into consideration that if you have to checkout multiple files, the tree population will also impact your performance, so I recommend this for a single file and only if the repo is large enough to be worth it all these actions.

cbuchart
  • 10,847
  • 9
  • 53
  • 93
  • I'm not sure why but both `tree:0` and `blob:none` appear to download unecessary tree objects on checkout. Test repo: https://github.com/cirosantilli/test-git-partial-clone-big-small which has some huge trees under `big_tree`. Do let me know if you ever find a solution. – Ciro Santilli OurBigBook.com Apr 29 '23 at 18:54
1

I am adding this answer as an alternative to doing a formal checkout or some similar local operation. Assuming that you have access to the web interface of your Git provider, you might be able to directly view any file at a given desired commit. For example, on GitHub you may use something like:

https://github.com/hubotio/hubot/blob/ed25584f/src/adapter.coffee

Here ed25584f is the first 8 characters from the SHA-1 hash of the commit of interest, followed by the path to the source file.

Similary, on Bitbucket we can try:

https://bitbucket.org/cofarrell/stash-browse-code-plugin/src/06befe08

In this case, we place the commit hash at the end of the source URL.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

In codecommit (git version of Amazon AWS) you can do this:

aws codecommit \
  get-file --repository-name myrepo \
  --commit-specifier master \
  --file-path path/myfile \
  --output text \
  --query fileContent | 
base64 --decode > myfile
david.perez
  • 6,090
  • 4
  • 34
  • 57
1

if you have a file, locally changed (the one which messing with git pull) just do:

git checkout origin/master filename
  1. git checkout - switch branches or restore working tree files, (here we switching nothing, just overwriting file
  2. origin/master - your current branch or you can use specific revision-number for example: cd0fa799c582e94e59e5b21e872f5ffe2ad0154b,
  3. filename with path from project main directory (where directory .git lives) so if you have structure:

`.git

public/index.html

public/css/style.css

vendors

composer.lock`

and want reload index.html - just use public/index.html

zoore
  • 293
  • 5
  • 13
0

It sounds like you're trying to carry over an idea from centralized version control, which git by nature is not - it's distributed. If you want to work with a git repository, you clone it. You then have all of the contents of the work tree, and all of the history (well, at least everything leading up to the tip of the current branch), not just a single file or a snapshot from a single commit.

 git clone /path/to/repo
 git clone git://url/of/repo
 git clone http://url/of/repo
Cascabel
  • 479,068
  • 72
  • 370
  • 318
0

I don’t see what worked for me listed out here so I will include it should anybody be in my situation.

My situation, I have a remote repository of maybe 10,000 files and I need to build an RPM file for my Linux system. The build of the RPM includes a git clone of everything. All I need is one file to start the RPM build. I can clone the entire source tree which does what I need but it takes an extra two minutes to download all those files when all I need is one. I tried to use the git archive option discussed and I got “fatal: Operation not supported by protocol.” It seems I have to get some sort of archive option enabled on the server and my server is maintained by bureaucratic thugs that seem to enjoy making it difficult to get things done.

What I finally did was I went into the web interface for bitbucket and viewed the one file I needed. I did a right click on the link to download a raw copy of the file and selected “copy shortcut” from the resulting popup. I could not just download the raw file because I needed to automate things and I don’t have a browser interface on my Linux server.

For the sake of discussion, that resulted in the URL:

https://ourArchive.ourCompany.com/projects/ThisProject/repos/data/raw/foo/bar.spec?at=refs%2Fheads%2FTheBranchOfInterest

I could not directly download this file from the bitbucket repository because I needed to sign in first. After a little digging, I found this worked: On Linux:

echo "myUser:myPass123"| base64
bXlVc2VyOm15UGFzczEyMwo=

curl -H 'Authorization: Basic bXlVc2VyOm15UGFzczEyMwo=' 'https://ourArchive.ourCompany.com/projects/ThisProject/repos/data/raw/foo/bar.spec?at=refs%2Fheads%2FTheBranchOfInterest' > bar.spec

This combination allowed me to download the one file I needed to build everything else.

user1683793
  • 1,213
  • 13
  • 18
0

Yes you can this by this command which download one specific file

wget -o <DesiredFileName>  <Git FilePath>\?token\=<personalGitToken>

example

wget -o javascript-test-automation.md https://github.com/akashgupta03/awesome-test-automation/blob/master/javascript-test-automation.md\?token\=<githubPersonalTone>
Akash
  • 291
  • 1
  • 4
  • 5
0

git checkout <other-branch> -- <single-file> works for me on git.2.37.1.
However, the file is (git-magically) staged for commit and I can not see git diff properly.
I then run git restore --staged db/structure.sql to unstage it.

That way I DO have the file in the exact version that I want and I can see the difference with other versions of that file.

aerijman
  • 2,522
  • 1
  • 22
  • 32
-3

If you have edited a local version of a file and wish to revert to the original version maintained on the central server, this can be easily achieved using Git Extensions.

  • Initially the file will be marked for commit, since it has been modified
  • Select (double click) the file in the file tree menu
  • The revision tree for the single file is listed.
  • Select the top/HEAD of the tree and right click save as
  • Save the file to overwrite the modified local version of the file
  • The file now has the correct version and will no longer be marked for commit!

Easy!

-4

If you only need to download the file, no need to check out with Git.

GitHub Mate is much easier to do so, it's a Chrome extension, enables you click the file icon to download it. also open source

Cam Song
  • 2,956
  • 1
  • 22
  • 18