Working with multiple GitHub accounts on the same machine can be tricky, but we can automate account switching when changing workspaces. Here’s my solution using Fish Shell and Direnv.
Prerequisites
Install direnv, this handy tool automatically loads environment variables when you cd into directories.
The Setup
Add this function to your Fish Shell configuration:
function __gh_auth_switch_gh_account --on-variable GH_ACCOUNT
if test -n "$GH_ACCOUNT"
gh auth switch --user "$GH_ACCOUNT"
end
endHow it works
Let’s break down the snippet:
--on-variabletells Fish Shell to run this function when the variableGH_ACCOUNTchanges value.test -n $GH_ACCOUNTreturns true if the length ofGH_ACCOUNTis non-zero.gh auth switch --user "$GH_ACCOUNT"switches the active account to$GH_ACCOUNT.
For example, if we need to switch to gh-user-1 under path/to/company/ . We can add a .envrc file under path/to/company:
export GH_ACCOUNT=gh-user-1When we cd into path/to/company/project1, direnv will set the GH_ACCOUNT variable automatically, and the callback function __gh_auth_switch_gh_account will be invoked by the Fish Shell to make gh-user-1 active.
发表回复