Skip to content

Exit status 5 from git when running gh repo set-default #7770

Open

Description

@waldyrious

Describe the bug

I have a local clone of repository which I forked to submit a PR. However, when running gh pr create, I mistakenly selected my fork in the answer to Where should we push the 'foobar' branch? (due to the switcharoo that gh does when forking a repo).

When I noticed the error, I closed the PR in my fork and attempted to set the upstream repo as the default for PRs, by doing gh repo set-default. This resulted in the following output:

$ gh repo set-default 
This command sets the default remote repository to use when querying the
GitHub API for the locally cloned repository.

gh uses the default repository for things like:

 - viewing and creating pull requests
 - viewing and creating issues
 - viewing and creating releases
 - working with Actions
 - adding repository and environment secrets

? Which repository should be the default? gnunn1/tilix
failed to run git: exit status 5

Note the error at the bottom: "failed to run git: exit status 5".

However, running gh pr create afterwards does show that the default remote was indeed set, so I'm not sure what the error message is about.

Steps to reproduce the behavior

  1. Run gh repo set-default
  2. Select one of the remotes and press Enter
  3. See error mentioned above

Expected vs actual behavior

I expected the error message not to appear.

Activity

  1. added
    bug
    on Jul 31, 2023
  2. added
    needs-triage
    on Jul 31, 2023
  3. harveysanders commented on Jul 31, 2023

    @harveysanders
    Contributor

    @waldyrious What OS are you using?

  4. harveysanders commented on Jul 31, 2023

    @harveysanders
    Contributor

    @waldyrious It could be an issue with git's permissions on your system. If you're using VSCode, you can use the debugger to run the repo set-default command and get a clearer understanding of where the error occurred. Here's an example of a VSCode launch.json config to get it working:

    {
      // Use IntelliSense to learn about possible attributes.
      // Hover to view descriptions of existing attributes.
      // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
      "version": "0.2.0",
      "configurations": [
        {
          "name": "Run 'gh repo set-default'",
          "type": "go",
          "request": "launch",
          "mode": "auto",
          "args": [
            "repo",
            "set-default"
          ],
          "cwd": "<the path to a repo you want to run set-default on>",
          "program": "${workspaceFolder}/cmd/gh",
          "console": "integratedTerminal"
        }
      ]
    }

    I'm guessing the error is happening somewhere around here:

    if currentDefaultRepo != nil {
    if err := opts.GitClient.UnsetRemoteResolution(
    ctx.Background(), currentDefaultRepo.Name); err != nil {
    return err
    }
    }
    if err = opts.GitClient.SetRemoteResolution(
    ctx.Background(), selectedRemote.Name, resolution); err != nil {
    return err
    }
    if opts.IO.IsStdoutTTY() {
    cs := opts.IO.ColorScheme()
    fmt.Fprintf(opts.IO.Out, "%s Set %s as the default repository for the current directory\n", cs.SuccessIcon(), ghrepo.FullName(selectedRepo))
    }

    You can pop a breakpoint in and step through to see if you can get more information on what's happening.

    I hope that is somewhat helpful

  5. samcoe commented on Jul 31, 2023

    @samcoe
    Contributor

    @waldyrious From the git docs: "you try to unset an option which does not exist (ret=5)". When doing repo set-default we try to unset the previously set default repo and it is likely this git command that is failing. It is a bit of a mystery as to why though. We do a check to make sure there was a previously set default before running the unset operation. Are you able to reproduce this error? If so, it would be helpful if you could paste the git config file for the repo, redacted as necessary. Also, running the command with GH_DEBUG=1 environment variable set will help verify my above hypothesis about the unset command being the culprit.

  6. added
    more-info-needed
    and removed
    needs-triage
    on Jul 31, 2023
  7. added
    gh-repo
    on Oct 3, 2023
  8. changed the title [-]Git error when running `gh repo set-default`[/-] [+]Exit status 5 from git when running `gh repo set-default`[/+] on Jan 16, 2024
  9. williammartin commented on Jan 16, 2024

    @williammartin
    Member

    Closing this due to inactivity but feel free to reopen if it's still an issue and we can move it forward.

  10. waldyrious commented on Mar 6, 2025

    @waldyrious
    ContributorAuthor

    OMG, I'm so sorry! I somehow totally missed the notifications for this issue.

    I can still reproduce the error (with gh version 2.67.0). Here's the output with the debug flag set (in another repository):

    $ GH_DEBUG=1 gh repo set-default facebook/docusaurus
    [git rev-parse --git-dir]
    [git remote -v]
    [git config --get-regexp ^remote\..*\.gh-resolved$]
    * Request at 2025-03-06 18:13:06.339930868 +0000 WET m=+0.087984152
    * Request to https://api.github.com/graphql
    * Request took 636.184213ms
    [git config --unset remote.origin.gh-resolved]
    failed to run git: exit status 5

    For reference, here's the output of the git commands listed above:

    $ git rev-parse --git-dir
    .git
    
    $ git remote -v
    origin	[email protected]:waldyrious/docusaurus.git (fetch)
    origin	[email protected]:waldyrious/docusaurus.git (push)
    upstream	[email protected]:facebook/docusaurus.git (fetch)
    upstream	[email protected]:facebook/docusaurus.git (push)
    
    $ git config --get-regexp '^remote\..*\.gh-resolved$'
    remote.origin.gh-resolved base
    
    $ git config --unset remote.origin.gh-resolved
    
    $ echo $?
    5

    Let me know if there are any additional input you'd need to debug the issue!

    Closing this due to inactivity but feel free to reopen if it's still an issue and we can move it forward.

    @williammartin I don't have the permissions to reopen, but please do so if you can. I promise I'll be more responsive this time! 😅

  11. williammartin commented on Mar 7, 2025

    @williammartin
    Member

    That's very strange! If possible can you share the entire .git/config file?

  12. harveysanders commented on Mar 7, 2025

    @harveysanders
    Contributor

    For more context, exit code 5 can also happen if there are multiple matches:

    • you try to unset an option which does not exist (ret=5),"
    • you try to unset/set an option for which multiple lines match (ret=5), or

    https://www.kernel.org/pub/software/scm/git/docs/git-config.html

    It looks like there's only one though, per your regexp...hmm

  13. 1 remaining item

  14. waldyrious commented on Mar 10, 2025

    @waldyrious
    ContributorAuthor

    Re-reading the opening comment, I believe the reproduction steps may indeed be related to selecting the wrong remote to push a branch when creating a PR. Here's what I wrote back then:

    when running gh pr create, I [...] selected my fork in the answer to Where should we push the 'foobar' branch? [...]

    When I noticed the error, I closed the PR in my fork and attempted to set the upstream repo as the default for PRs, by doing gh repo set-default. This resulted in the [error described in this issue].

    This was exactly what happened this time again, with a different repo: the PR I tried to create with gh pr create was created in my fork instead of in the upstream repo (I did select my repo as the answer to the "Where should we push the 'foobar' branch?" question), so I attempted to use set-default and ran into the same exit code 5 issue.

  15. williammartin commented on Mar 11, 2025

    @williammartin
    Member

    From your provided git config, I cannot see how this would possibly happen:

    git config --get-regexp '^remote\..*\.gh-resolved$'
    remote.origin.gh-resolved base
    

    Can you try running it again just to double check? Very strange!

  16. waldyrious commented on Mar 11, 2025

    @waldyrious
    ContributorAuthor

    Can you try running it again just to double check? Very strange!

    Sure:

    Image

  17. williammartin commented on Mar 11, 2025

    @williammartin
    Member

    Ah, I meant without running any other commands. Running repo set-default might have altered your git config. At this point, without any further commands, can you copy and paste your .git/config again please? Hard to see how the get would work but the delete wouldn't.

    Could you run git config --list --show-origin | grep gh-resolved from inside the git repository as well? This would hopefully tell us which file the config might be coming from.

  18. ardnew commented on Jan 1, 2026

    @ardnew

    I'm also encountering this same issue.

    $ git config --list --show-origin | grep gh-resolved
    file:/home/andrew/.config/git/config	remote.origin.gh-resolved=base

    Apologies for the long .gitconfig. Didn't want to snip something I didn't realize was important to the issue:

    /home/andrew/.config/git/config

    —

    (click me)

    # vim: ai noet sw=2 ts=2 ft=gitconfig
    
    [user]
    	name = andrew
    	email = [email protected]
    	signingKey = 408928164F4BBA89600CA258695575CCC8816281
    	useConfigOnly = true
    
    [author]
    	name = ardnew
    	email = [email protected]
    
    [committer]
    	name = ardnew
    	email = [email protected]
    
    [http]
    	cookiefile = ~andrew/.config/git/cookies
    
    [url "ssh://[email protected]/"]
    	insteadOf = https://github.com/
    
    # ------------------------------------------------------------------------------
    #  Local workstation/system ettings  -------------------------------------------
    # ------------------------------------------------------------------------------
    
    [core]
    	editor = vim
    	fileMode = true
    	ignoreCase = false
    	protectNTFS = true	# we share files between Windows NTFS and Apple HFS+
    	protectHFS = true	#  filesystems, so keep both of these true.
    	excludesFile = ~andrew/.config/git/ignore # (default=${XDG_CONFIG_HOME}/git/ignore)
    #	excludesFile = %(prefix)/etc/gitignore
    
    [init]
    	defaultBranch = main
    
    # ------------------------------------------------------------------------------
    #  Git subcommand aliases  -----------------------------------------------------
    # ------------------------------------------------------------------------------
    
    # Shorthand for the most common operations.
    [alias]
    	sup  = fetch --all --tags --prune
    	ci   = commit
    	co   = checkout
    	stat = status --short --branch
    	mod  = submodule update --init --recursive
    	l = log --pretty=fuller --graph --stat --remove-empty
    	cont = rebase --continue
    	hist = l --follow --patch --text # pathspec history
    
    # Tools for analyzing the merge history of a repo using tree-like graphics
    [alias]
    	tree = log --no-show-signature --graph --date=format-local:%H:%M:%S \
    		--pretty="'%C(#ffe97b ul)%h%C(reset) %C(#568ea6)%cs\
     %C(#305f72)%cd%C(reset)%C(auto)%d%C(reset)\
     %s %C(yellow)(%C(reset)%C(#1abc9c)%an%C(reset)%C(yellow),%C(reset)\
     %C(#007055)%cr%C(reset)%C(yellow))%C(reset)'"
    
    # Some refinements to normal 'git tree' output for alternative perspectives.
    [alias "tree"]
    	branches = tree --simplify-by-decoration
    
    # Use checkout.remote to checkout a remote branch locally, replacing any
    # local branch of the same name. This will permanently discard any local 
    # changes that have not been pushed or stashed.
    #   Usage: git checkout.remote <remote> <branch>
    [alias "checkout"]
    	remote = "!bash -c 'git fetch --all &&" \
    		"git checkout \"${2}\" &&" \
    		"git reset --hard \"${1}/${2}\"'" -- "${@}"
    
    # Tools for finding details about our remote.
    [alias "remote"]
    	branch = rev-parse --abbrev-ref --symbolic-full-name @{u}
    	url = "!bash -c 'git remote get-url "$@"' -- " \
    		$( git remote.branch | cut -d/ -f1 )
    	checkout = checkout.remote
    
    # List the file system contents of branches similar to the normal filesystem tools.
    [alias]
    	ls = !bash -c 'git ls-tree --abbrev=7 -t --name-only \"${1}\"' --    ${1:-$( git remote.branch )}
    	lr = "!bash -c 'git ls-tree --abbrev=7 -t -r --name-only \"${1}\"' -- " \
    		${1:-$( git remote.branch )}
    	ll = "!bash -c 'git ls-tree --abbrev=7 -t -l --full-name \"${1}\"' -- " \
    		${1:-$( git remote.branch )}
    	llr = "!bash -c 'git ls-tree --abbrev=7 -t -r -l --full-tree \"${1}\"' -- " \
    		${1:-$( git remote.branch )}
    	cat = "!bash -c 'BAT_CONFIG_PATH=<( printf -- --file-name='%s' '"${1}"' );" \
    		"git show "${2}:${1}"' -- "${1}" "${2:-$( git remote.branch )}
    	ls-r = !bash -c 'git ls-tree --abbrev=7 -r -t --name-only \"${1}\"' --    ${1:-$( git remote.branch )}
    	st = status
    	br = branch
    
    # ------------------------------------------------------------------------------
    #  Tool preferences  -----------------------------------------------------------
    # ------------------------------------------------------------------------------
    
    [filter "lfs"]
    	required = true
    	clean = git-lfs clean -- %f
    	smudge = git-lfs smudge -- %f
    	process = git-lfs filter-process
    
    [color]
    	branch = auto
    	diff = auto
    	status = auto
    	showbranch = auto
    	ui = true
    
    #[color "branch"]
    #	current =
    #	local =
    #	remote =
    #	upstream =
    #	plain =
    
    [color "decorate"]
    	branch = "#7f71ff"
    	remoteBranch = "#ee4540"
    	tag = "#f18c8e" ul
    	stash = "#fcbb6d"
    	HEAD = "#ffbb00"
    
    [log]
    	abbrevCommit = false
    	decorate = full
    	showRoot = true
    	showSignature = false
    	date = format-local:%Y/%m/%d %H:%M:%S
    
    [status]
    	relativePaths = true
    	branch = true
    	aheadBehind = true
    	displayCommentPrefix = false
    	renames = copies
    	showStash = true
    	showUntrackedFiles = normal
    	submoduleSummary = true
    
    [diff]
    	algorithm = minimal
    	dirstat = lines,cumulative,0
    	context = 4
    	ignoreSubmodules = untracked
    	mnemonicPrefix = true
    	suppressBlankEmpty = true
    	colorMoved = default
    	submodule = diff
    	tool = bc5
    	guitool = bc5
    
    [difftool]
    	dirDiff = true
    	symlinks = false
    	prompt = false
    	trustExitCode = true
    
    [difftool "bc5"]
    	cmd = bcompare --expandall "$LOCAL" "$REMOTE"
    	
    [merge]
    	tool = vimdiff
    	guitool = bc5
    
    [mergetool]
    	prompt = false
    	trustExitCode = true
    	keepBackup = false
    	keepTemporaries = false
    
    [mergetool "bc5"]
    	cmd = bcompare "$LOCAL" "$REMOTE" "$BASE" "$MERGED"
    
    [interactive]
    	diffFilter = delta --color-only
    
    [delta]
    	navigate = true
    	side-by-side = true
    	line-numbers = true
    	dark = true
    	commit-decoration-style = "bold yellow box ul"
    	commit-style = "raw"
    	file-style = "bold yellow ul"
    	file-decoration-style = "none"
    	whitespace-error-style = "reverse bright-green"
    	zero-style = "dim syntax"
    
    [bat]
    	dark = true
    
    [stash]
    	showPatch = false
    	showStat = true
    
    [grep]
    	patternType = perl
    
    [tar]
    	umask = 0022
    
    [web]
    	browser = firefox
    
    [gpg]
    	program = gpg
    	format = openpgp
    
    # ------------------------------------------------------------------------------
    #  Version control operation configuration  ------------------------------------
    # ------------------------------------------------------------------------------
    
    [blame]
    	coloring = highlightRecent
    	showEmail = true
    
    [clone]
    	recurseSubmodules = on-demand
    
    [fetch]
    	recurseSubmodules = on-demand
    	parallel = 0
    	auto = true
    
    [checkout]
    	defaultRemote = ardnew
    
    [commit]
    	gpgSign = true
    	status = true
    
    [pull]
    	# used in conjunction with rebase.autoStash = true. this ensures ″pull″ only
    	# synchronizes all pushed changes. locally-committed or -uncommitted changes
    	# (anything not pushed) are then rebased on top of this synchronized update.
    	rebase = true
    
    [push]
    	default = simple
    	recurseSubmodules = on-demand
    #	gpgSign = true
    
    [rebase]
    	abbreviateCommands = true # easier to modify existing commands
    	autoStash = true
    	stat = true
    
    [tag]
    	forceSignAnnotated = true
    	gpgSign = true
    
    [submodule]
    	fetchJobs = 0
    #	recurse = true
    
    [remote "origin"]
    	gh-resolved = base
    
    [credential]
    	credentialStore = gpg
    	helper = 
    	helper = /opt/git-credential-manager/bin/git-credential-manager
    	gitHubAccountFiltering = false
    
  19. williammartin commented on Jan 6, 2026

    @williammartin
    Member

    @ardnew am I right in understanding that this repo is a dotfiles repo for you?

    There's something funny going on here that the file you have linked looks like a global git config but it has a remote block for gh-resolved. Is your dotfiles repo public somewhere, if this is the case?

    Do you also have a file /home/andrew/.config/.git/config and a /home/andrew/.gitconfig?

  20. ardnew commented on Jan 7, 2026

    @ardnew

    @williammartin no, not a dotfiles repo.

    There's something funny going on here that the file you have linked looks like a global git config but it has a remote block for gh-resolved. […]
    Do you also have a file /home/andrew/.config/.git/config [sic] and a /home/andrew/.gitconfig

    Nope, just the former.

    /home/andrew/.config/git/config is indeed my global gitconfig, and the fork in which I encountered the error is cloned to /opt/gogll/src.

    I too have never understood why gh relentlessly adds this to my global gitconfig, regardless of repo or path. I'll remove it, and the next gh command I run will reinsert it. It has done this for years, but I never believed it was causing an issue.

    Maybe [user.useConfigOnly] could be causing an issue? I don't have access to that PC at this very moment. Will verify and respond when I do.

  21. ChasmOfDeath commented on Jan 7, 2026

    @ChasmOfDeath
  22. williammartin commented on Jan 7, 2026

    @williammartin
    Member

    I too have never understood why gh relentlessly adds this to my global gitconfig, regardless of repo or path. I'll remove it, and the next gh command I run will reinsert it. It has done this for years, but I never believed it was causing an issue.

    😅 Well, this gh-resolved config key is supposed to be per repo to indicate which remote is the base (default). For example, when you clone a fork the upstream is set to the default e.g. in my fork of huh:

    [remote "upstream"]
            url = https://github.com/charmbracelet/huh.git
            fetch = +refs/heads/*:refs/remotes/upstream/*
            gh-resolved = base
    

    So something funny is going on if it is ending up in your global config for sure! That may or may not be related to the exit status 5 you are seeing, but definitely suspicious.

  23. waldyrious commented on Sep 3, 2026

    @waldyrious
    ContributorAuthor

    Coming back to this after a long while, I think I have now finally managed to get to the bottom of this. Indeed, as @williammartin probably suspected, and like @ardnew, the culprit in my case was a gh-resolved = base entry under [remote "origin"] in my global ~/.gitconfig, rather than anything in the repo-level .git/config I pasted above.

    Just to be clear, to avoid conflating two situations: in my case the global gh-resolved was not something gh kept reinserting; I had added it to my global ~/.gitconfig manually, years ago, to make gh always treat origin as the base repo (so I wouldn't have to manually run set-default in every fork after PR #6738 disabled the interactive default repo picker in gh pr create, replacing it with an error message 😢). When I switched to a new computer, I didn't set the config in my current ~/.gitconfig, and it was not automatically reinserted by gh; so I stopped bumping into the "exit 5" error (hence forgetting —again!— about this issue), and now instead have to run set-default whenever I fork a new repo. 🤷

    So, from what I could gather, here's what is causing the issue: gh repo set-default decides whether a default is already set via remotes.ResolvedRemote(), which is populated by reading git config --get-regexp '^remote\..*\.gh-resolved$'; the problem is that, with no scope flag, git config reads the merged configuration across system/global/local, so gh sees the entry coming from the global ~/.gitconfig and concludes there's a current default to clear. It then calls UnsetRemoteResolution, which runs git config --unset remote.origin.gh-resolved, and that command, with no --global/--local flag, defaults to writing the repo-local config. Since the entry isn't in the local config (it's global), git finds nothing local to unset and returns exit 5 ("trying to unset an option which does not exist"), which gh surfaces as failed to run git: exit status 5.

    So the underlying issue is an asymmetry between gh's read and write paths for the gh-resolved config: the resolution is read across all config scopes, but the unset action only targets the local scope.

    Here are the self-contained reproduction steps, using an isolated HOME/config to avoid interference with the real git config (no gh or network needed, since the bug is purely about the git config commands that gh invokes):

    # Point $HOME at a throwaway temp dir, and the global git config at a file within it (for the current shell session only)
    $ export HOME=$(mktemp -d)
    $ export GIT_CONFIG_GLOBAL="$HOME/.gitconfig"
    
    # The root cause: a gh-resolved entry in the *global* config
    $ git config --global remote.origin.gh-resolved base
    
    # Demo: a repo with an 'origin' remote but no *local* gh-resolved
    $ git init -q "$HOME/repo" && cd "$HOME/repo"
    $ git remote add origin https://github.com/octocat/Hello-World.git
    
    # Confirm that gh's detection reads the merged local+global config, and thus sees the global entry:
    $ git config --get-regexp '^remote\..*\.gh-resolved$'
    remote.origin.gh-resolved base
    
    # Confirm that the local scope config is empty:
    $ git config --local --get-regexp '^remote\..*\.gh-resolved$'; echo "exit: $?"
    exit: 1
    
    # The kicker: The unset that gh runs (local-scoped by default) fails with exit 5:
    $ git config --unset remote.origin.gh-resolved; echo "exit: $?"
    exit: 5

    When the gh-resolved entry is instead present locally (which happens after one runs gh repo set-default), the same unset succeeds (exit 0). My global gh-resolved config entry was a manual workaround to gh's default forking flow, rather than something gh does (or offers to do, even), which explains why most people never hit this.

    IMHO the right fix for this bug would be for gh's paths for detection and unsetting of gh-resolved to agree on git config scope.

    One approach would be to have both read only local config, so that a global gh-resolved doesn't get detected as a clearable local default in the first place. That matches what @williammartin said above:

    this gh-resolved config key is supposed to be per repo

    That said, the reason I and @ardnew felt the need to specify it as a global key was precisely to set this once as a default and avoid having to configure each repo individually, and forcing the reading of gh-resolved to ignore the global config would break our use case (and the usual expectations for how git's configuration scopes are supposed to cascade). So IMHO the correct solution would be to skip the clearing of gh-resolved if it is not defined in the local repo, thus avoiding the exit 5 issue.

    I'll prepare a PR to fix this, which, after all this time and effort from everyone involved, seems like the least I could do! 😅

  24. removed
    more-info-needed
    on Sep 3, 2026
  25. williammartin commented on Sep 3, 2026

    @williammartin
    Member

    @waldyrious thanks for the detailed investigation! Always handy to have the additional information.

    Regarding preparing PRs, we're absolutely slammed at the moment with agents going brrrr, so unfortunately we have little time to get round to reviewing external PRs. You can create it and it might be useful for us to see in future, but honestly it may not go anywhere and I don't want you to waste your time.

  26. added
    priority-3
    on Sep 3, 2026
  27. waldyrious commented on Sep 3, 2026

    @waldyrious
    ContributorAuthor

    Ah, no problem, and thanks for the heads-up! I'll refrain from submitting a PR but will try to provide timely feedback (famous last words, amirite? 🫣) once one is opened. 😃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    buggh-repopriority-3

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions