3

How can I obtain the remote used when issuing git push?

I want to be able to use this in a script, or in git alises.

Related: Default remote for git fetch

Tom Hale
  • 40,825
  • 36
  • 187
  • 242

3 Answers3

3

The answer is not as simple as for fetching, because there is a list of fallbacks which need to be considered:

These aliases take into account all of the above:

branch-name = "symbolic-ref --short HEAD"  # https://stackoverflow.com/a/19585361/5353461
branch-remote-fetch = !"branch=$(git branch-name \"$1\") && git config branch.\"$branch\".remote || echo origin #"
branch-remote-push  = !"branch=$(git branch-name \"$1\") && git config branch.\"$branch\".pushRemote || git config remote.pushDefault || git branch-remote-fetch #"

And, as a bonus, for the URL:

branch-url-push = !"remote=$(git branch-remote-push  \"$1\") && git remote get-url --push \"$remote\" #"  # cognizant of pushInsteadOf
Tom Hale
  • 40,825
  • 36
  • 187
  • 242
2

Depending on whether you want the remote's name or its URL, also

git push --dry-run --porcelain --verbose

and looking at the URL after "To " in the first line might do.

sschuberth
  • 28,386
  • 6
  • 101
  • 146
  • `Enter passphrase for /home/ravi/.ssh/XXXX:` `git-receive-pack: permission denied: XXXX` `fatal: Could not read from remote repository.` `Please make sure you have the correct access rights and the repository exists.` – Tom Hale Oct 21 '18 at 09:38
  • Or: `fatal: No configured push destination.` `Either specify the URL from the command-line or configure a remote repository using...` – Tom Hale Oct 21 '18 at 09:40
  • 1
    Well, of course `--dry-run` only works if a real push would work. If you want to be able to get the remote a push would use even if a real push would fail you should probably make that more clear in your question. – sschuberth Oct 21 '18 at 09:46
  • In any case, if you add `--verbose`, the URL is still printed. – sschuberth Oct 21 '18 at 09:53
1

This works for me:

$ git remote get-url --push origin

From the docs here:

**get-url**

Retrieves the URLs for a remote. Configurations for insteadOf and pushInsteadOf are expanded here. By default, only the first URL is listed.

With --push, push URLs are queried rather than fetch URLs.

With --all, all URLs for the remote will be listed.
SeanRtS
  • 1,005
  • 1
  • 13
  • 31