Check if git remote exists before first push
I'm writing a bash script and I need a test to see whether a given remote exists.
Suppose, for concreteness, that I want to test whether the remote faraway
exists. If I've pushed something to faraway
, I can do if [ -d .git/refs/remotes/faraway ]; then ...
. But as far as I can see, the alias faraway
can still be defined even if .git/refs/remotes/faraway
does not exist.
One other option is to parse through the output of git remote
and see if faraway
appears there. But I'm wondering whether there is an easier way of checking whether faraway
is defined, regardless of whether .git/refs/remotes/faraway/
exists.
Solution 1:
One thought: You could test exit status on git ls-remote faraway
. This will actually force communication with the remote, instead of just looking for its presence or absence locally.
if git ls-remote --exit-code faraway; then
....
fi
Solution 2:
Another way to check if faraway
is defined in .git/config
:
if git config remote.faraway.url > /dev/null; then
…
fi
To check if faraway
isn't defined, prefix the condition with !
:
if ! git config remote.faraway.url > /dev/null; then
…
fi
Solution 3:
If the remote is defined in .git/config
, you can avoid pinging the remote server with git remote
.
if git remote | grep faraway > /dev/null; then
...
fi