Let's say, for example, I have 3 remotes defined in my .git/config in the following order:
remote3
remote1
remote2
Also, checkout.defaultRemote may or may not be set.
Then, there is a branch my_branch that is not present locally but it is on at least 1 remote. (They are all fetched.)
Can I write a script that (without changing the state of anything in the repository) will predict which remote would be used if I run git switch my_branch?
Yes you can.
Behavior of git switch is well described in documentation:
Git - git-switch Documentation
--guess
--no-guessIf is not found but there does exist a tracking branch in exactly one remote (call it ) with a matching name, treat as equivalent to
$ git switch -c --track /
If the branch exists in multiple remotes and one of them is named by the
checkout.defaultRemoteconfiguration variable, we’ll use that one for the purposes of disambiguation, even if the isn’t unique across all remotes. Set it to e.g.checkout.defaultRemote=originto always checkout remote branches from there if is ambiguous but exists on the origin remote. See alsocheckout.defaultRemotein git-config[1].
--guessis the default behavior. Use--no-guessto disable it.
So first you need to list possible branches:
git for-each-ref --format='%(refname)' "refs/remotes/*/my_branch"
Check what what is the default remote (it can be not set):
git config --get checkout.defaultRemote
With this knowledge you can write a script which will determine what will be selected by git switch. Sadly it is not a one-liner.