Git: How to pull a single file from a server repository in Git?

Short Answer

It is possible to do (in the deployed repository):

git fetch --all
// git fetch will download all the recent changes, but it will not put it in your current checked out code (working area).

Followed by:

git checkout origin/master -- path/to/file
// git checkout <local repo name (default is origin)>/<branch name> -- path/to/file will checkout the particular file from the downloaded changes (origin/master).

Full Example

$ cd /project/directory

$ git branch
* develop

check the remote name

$ git remote -v
origin [email protected]:abc/123.git

Confirmed it's origin and

I am on branch develop and need a file from branch main

File i need is src/scss/main.scss

git fetch --all
git checkout origin/main -- src/scss/main.scss

git fetch --all
git checkout origin/master -- <your_file_path>
git add <your_file_path>
git commit -m "<your_file_name> updated"

This is assuming you are pulling the file from origin/master.


This can be the solution:

git fetch

git checkout origin/master -- FolderPathName/fileName

Thanks.


I was looking for slightly different task, but this looks like what you want:

git archive --remote=$REPO_URL HEAD:$DIR_NAME -- $FILE_NAME |
tar xO > /where/you/want/to/have.it

I mean, if you want to fetch path/to/file.xz, you will set DIR_NAME to path/to and FILE_NAME to file.xz. So, you'll end up with something like

git archive --remote=$REPO_URL HEAD:path/to -- file.xz |
tar xO > /where/you/want/to/have.it

And nobody keeps you from any other form of unpacking instead of tar xO of course (It was me who need a pipe here, yeah).


This scenario comes up when you -- or forces greater than you -- have mangled a file in your local repo and you just want to restore a fresh copy of the latest version of it from the repo. Simply deleting the file with /bin/rm (not git rm) or renaming/hiding it and then issuing a git pull will not work: git notices the file's absence and assumes you probably want it gone from the repo (git diff will show all lines deleted from the missing file).

git pull not restoring locally missing files has always frustrated me about git, perhaps since I have been influenced by other version control systems (e.g. svn update which I believe will restore files that have been locally hidden).

git reset --hard HEAD is an alternative way to restore the file of interest as it throws away any uncommitted changes you have. However, as noted here, git reset is is a potentially dangerous command if you have any other uncommitted changes that you care about.

The git fetch ... git checkout strategy noted above by @chrismillah is a nice surgical way to restore the file in question.