Skip to content

Instantly share code, notes, and snippets.

@WomB0ComB0
Created September 15, 2025 00:55
Show Gist options
  • Select an option

  • Save WomB0ComB0/46d666d0934e2a99c7ec16f0b0ed9955 to your computer and use it in GitHub Desktop.

Select an option

Save WomB0ComB0/46d666d0934e2a99c7ec16f0b0ed9955 to your computer and use it in GitHub Desktop.
gha - Enhanced with AI-generated documentation
#!/bin/bash
# This script wraps 'gh auth switch' and updates git user.name and user.email.
# Function to set git user config
set_git_config() {
local name="$1"
local email="$2"
echo "Setting git config: name='$name', email='$email'"
git config --global user.name "$name"
git config --global user.email "$email"
}
# Function to get the currently active GitHub user
get_active_user() {
local output
output=$(gh auth status 2>&1)
# Debug: show the actual output (optional - remove if too verbose)
# echo "DEBUG: gh auth status output:"
# echo "$output"
# echo "---"
# Try multiple parsing approaches
local active_user=""
# Method 1: Look for "Active account: true" and find the associated username
active_user=$(echo "$output" | awk '
/Logged in to.*account/ {
match($0, /account ([^[:space:]]*) /, arr)
username = arr[1]
}
/Active account: true/ && username != "" {
print username
exit
}
')
if [[ -n "$active_user" ]]; then
echo "$active_user"
return 0
fi
# Method 2: Look for "Logged in to github.com account <username> (Active)"
if [[ "$output" =~ Logged\ in\ to\ [^[:space:]]*\ account\ ([^[:space:]]*)[[:space:]]*\(.*Active.*\) ]]; then
active_user="${BASH_REMATCH[1]}"
echo "$active_user"
return 0
fi
# Method 3: Look for the currently selected account in a simpler format
if [[ "$output" =~ github\.com[[:space:]]+([^[:space:]]+)[[:space:]]+\(.*\*.*\) ]]; then
active_user="${BASH_REMATCH[1]}"
echo "$active_user"
return 0
fi
# If we get here, we couldn't find the active user
return 1
}
echo "Running gh auth switch..."
# Pass all arguments to gh auth switch
if ! gh auth switch "$@"; then
echo "Error: gh auth switch failed"
exit 1
fi
echo "Getting active user..."
active_user=$(get_active_user)
if [[ -z "$active_user" ]]; then
echo "Error: Could not determine active GitHub user."
echo "Please run 'gh auth status' manually to check the output format."
exit 1
fi
echo "Active GitHub user: '$active_user'"
# Set git config based on active user
case "$active_user" in
"WomB0ComB0")
set_git_config "<Username>" "<Email>"
;;
*)
echo "Active GitHub user is '$active_user'. No specific git config rule found for this user."
echo "Please manually set your git config if needed or add a rule for '$active_user'."
exit 1
;;
esac
echo "Done."

gha

File Type: TXT
Lines: 92
Size: 2.4 KB
Generated: 9/14/2025, 8:55:20 PM


This is a Bash script designed to automate the process of switching GitHub accounts using the gh auth switch command and then updating the Git user configuration (name and email) based on the active GitHub user.

Here's a breakdown of the script's functionality:

1. Script Purpose:

The script aims to streamline the process of switching between GitHub accounts using the gh auth switch command and automatically updating the Git user configuration (name and email) to match the active GitHub user. This is useful for developers who work with multiple GitHub accounts, each potentially associated with different identities or projects.

2. Key Functions:

  • set_git_config():

    • Takes a name and email as input.
    • Uses git config --global to set the global Git user name and email.
    • Provides informative output to the console.
  • get_active_user():

    • Executes gh auth status to retrieve the current authentication status.
    • Parses the output of gh auth status to determine the currently active GitHub username.
    • Employs multiple parsing strategies to accommodate variations in the output format of gh auth status.
    • Returns the active username or an empty string if it cannot be determined.
    • Includes debugging output (commented out) to aid in troubleshooting parsing issues.

3. Script Execution Flow:

  1. gh auth switch "$@": Executes the gh auth switch command, passing all arguments received by the script to it. This allows the script to be used as a wrapper for gh auth switch. If gh auth switch fails, the script exits with an error.

  2. get_active_user(): Calls the get_active_user function to determine the currently active GitHub user. If the active user cannot be determined, the script exits with an error message instructing the user to run gh auth status manually.

  3. case statement: Uses a case statement to determine the appropriate Git user configuration based on the active GitHub user.

    • Specific User Configuration: If the active user matches a predefined case (e.g., "WomB0ComB0"), the set_git_config function is called with the corresponding name and email. The example shows placeholder values for name and email ("<Username>" and "<Email>") which should be replaced with actual values.

    • Default Case: If the active user does not match any of the predefined cases, a message is printed to the console indicating that no specific Git configuration rule was found for that user. The script then exits, prompting the user to manually configure their Git settings or add a new rule to the script.

4. Error Handling:

  • The script includes error handling to check for failures in gh auth switch and get_active_user.
  • If an error occurs, an informative message is printed to the console, and the script exits with a non-zero exit code.

5. Improvements and Considerations:

  • User Configuration: The case statement provides a hardcoded mapping between GitHub usernames and Git configurations. A more flexible approach would be to store this mapping in an external configuration file (e.g., JSON or YAML) to avoid modifying the script directly.

  • Email Retrieval: Instead of hardcoding the email address, the script could attempt to retrieve the email address associated with the GitHub user using the GitHub API. This would require authentication with the GitHub API.

  • Idempotency: The script currently sets the Git configuration every time it is run, even if the configuration is already correct. It could be improved to check the current Git configuration and only update it if necessary.

  • Security: Avoid storing sensitive information (e.g., API tokens) directly in the script. Use environment variables or a secure configuration management system.

  • Output Parsing Robustness: The get_active_user function uses multiple parsing methods to handle variations in the output of gh auth status. However, the output format of gh auth status could change in future versions of the GitHub CLI. It is important to monitor for such changes and update the parsing logic accordingly. Consider using a more robust parsing method, such as a dedicated JSON parser if gh auth status supports JSON output.

  • Error Reporting: The script could provide more detailed error messages to aid in troubleshooting. For example, it could include the full output of gh auth status in the error message if the active user cannot be determined.

In summary, this script provides a useful automation tool for developers who frequently switch between GitHub accounts. By wrapping the gh auth switch command and automatically updating the Git user configuration, it simplifies the process of managing multiple GitHub identities. However, the script could be further improved by adding features such as external configuration, email retrieval, idempotency, and more robust error handling.


Description generated using AI analysis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment