Jeff Bailey
Written by Jeff Bailey

Learning resources, opinions, and facts about technology.

How Do I Use Multiple GitHub Accounts?

Reading Time: 1.4 minutes
Listen to this post

How do I use multiple GitHub accounts on the same computer?

When working on multiple projects from multiple clients this is a lifesaver.

1) Create a new SSH key on macOS. (Try on other OSes; YMMV)

ssh_key_gen() {
    if [ $# == 0 ]; then
        echo "Usage: ${FUNCNAME} [EMAIL] [KEY_NAME]"
        echo "1. Generate a key"
        echo "2. Copy the public key to the clipboard"
        return
    fi

    email="$1"
    key_name="$2"
    rsa_key_name="id_rsa_${key_name}"
    rsa_key_path="${HOME}/.ssh/${rsa_key_name}"

    ssh-keygen \
        -t rsa \
        -C "${email}" \
        -f "${rsa_key_path}" \

    cat "${rsa_key_path}.pub" | pbcopy
    ssh-add "${rsa_key_path}"

ssh_config_entry=$(cat <<-END

Host github.com
  HostName github.com
  User git
  IdentityFile "${rsa_key_path}"

END
)
    ssh_config_path="${HOME}/.ssh/config"
    if ! grep "${ssh_key_name}" "${ssh_config_path}"; then
        echo "Key already exists in ${ssh_config_path}"
    else
        echo "${ssh_config_entry}" >> "${ssh_config_path}"
    fi

}
ssh_key_gen your.email@domain.com your_key_name

2) Enter your passphrase.

3) Add a new ssh key in GitHub.

4) Now, test your key by cloning a repository.

To switch between keys run these commands.

ssh-add -D # Deletes all your keys
ssh-add ~/.ssh/id_rsa # Switch to your primary ssh key, do all the things
ssh-add -D # Deletes your primary key
ssh-add ~/.ssh/your_key_name # Switch to your secondary, or whatever key
# Profit?!

That's it, add all your SSH keys today.

Bonus! 🎉

Delete & list functions.

ssh_key_delete() {
    if [ $# == 0 ]; then
        echo "Usage: ${FUNCNAME} [KEY_NAME]"
        echo "1. Delete a key"
        return
    fi

    key_name="$1"
    rsa_key_name="id_rsa_${key_name}"
    rsa_key_path="${HOME}/.ssh/${rsa_key_name}"

    ssh-add -D "${rsa_key_name}" \
    && rm -f "${rsa_key_path}"* \
    || echo "Delete failed: ${rsa_key_path}"
}

ssh_key_list() {
    ssh-add -L
}

Enjoy!