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

后端 未结 2 986
北荒
北荒 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= 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
    

提交回复
热议问题