How to switch GitHub CLI account automatically

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
end

How it works

Let’s break down the snippet:

  1. --on-variable tells Fish Shell to run this function when the variable GH_ACCOUNT changes value.
  2. test -n $GH_ACCOUNT returns true if the length of GH_ACCOUNT is non-zero.
  3. 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-1

When 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.

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Index