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

This approach is a sanity saver when working on various projects from numerous clients.

  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
  1. Enter your passphrase.
  2. Add a new ssh key in GitHub.
  3. 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!

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
}