How do I check if a file exists in a remote?

后端 未结 2 973
北荒
北荒 2020-12-15 06:39

Is there a way to check if a file under specified, relative path exist in a remote? I\'m fine with fetching the info first if it\'s the only option. In other words I\'m look

相关标签:
2条回答
  • 2020-12-15 07:05

    You can use git archive to access individual files without downloading any other part of a repository:

    if git archive --format=tar \
                   --remote=<remote_name-or-URL> master README >/dev/null; then
      echo 'master has README'
    else
      echo 'master does not have README (or other error)'
    fi
    

    The archive service (upload-archive) may not be enabled on all servers or repositories though, you will have to test it for the servers and repositories that you need to access.

    If the archive service is not available, you will have to fetch objects through normal means.

    If you do not already have a remote setup for the repository in question you can do a “shallow” fetch into FETCH_HEAD (this needs to be done in a Git repository, but it can be completely unrelated or even empty):

    git fetch --depth=1 remote_name-or-URL master
    if git rev-parse --verify --quiet FETCH_HEAD:README >/dev/null; then
      echo "repository's master has README"
    else
      echo "repository's master does not have README"
    fi
    

    If you have a remote defined for the repository, then you probably just want to update it and access the file through the normal remote-tracking branches:

    git fetch remote_name
    if git rev-parse --verify --quiet remote_name/master:README >/dev/null; then
      echo "remote's master has README"
    else
      echo "remote's master does not have README"
    fi
    
    0 讨论(0)
  • 2020-12-15 07:18

    You can use

    git cat-file -e <remote>:<filename>
    

    which will exit with zero when the file exists. Instead of <remote> above you'd use a remote branch name (but it could in fact be any tree-ish object reference). To use such a remote branch, you'll need to have the remote repository configured and fetched (i.e. by using git remote add + git fetch).

    A concrete example:

    $ git cat-file -e origin/master:README && echo README exists
    README exists
    
    $ git cat-file -e origin/master:FAILME
    fatal: Not a valid object name origin/master:FAILME
    

    Two things to note:

    • Use / as path delimiter in filenames, even on e.g. Windows.
    • <filename> is a full path (such as foo/bar/README), relative to the root of the repository.
    0 讨论(0)
提交回复
热议问题