Search code examples
gitgit-mergegit-pullgit-fetch

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


I am working on a site with a server running Git. I am using Git for deployment (not GitHub). This was set up prior to my involvement using a hook method, and I referred to this question and entered the commands below, but it didn't work.

How do I pull a single file from the server? For instance, if I wanted to update my local file index.php? git pull index.php?


Solution

  • 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 git@github.com: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