Skip to content

Instantly share code, notes, and snippets.

@trouni
Last active July 25, 2023 02:55
Show Gist options
  • Save trouni/3afc274e0a12110cfb5c8cc9448e84b2 to your computer and use it in GitHub Desktop.
Save trouni/3afc274e0a12110cfb5c8cc9448e84b2 to your computer and use it in GitHub Desktop.
Get username from `origin` remote repository URL
#!/bin/bash
# Get the remote URL of the 'origin' remote
remote_url=$(git config --get remote.origin.url)
# Function to extract username from 'https://' URL
extract_username_from_https() {
# Remove 'https://' and trailing '.git' from the URL
url_without_protocol=${remote_url#https://}
url_without_protocol=${url_without_protocol%.git}
# Extract the username from the URL (everything before the first '/')
username=${url_without_protocol%%/*}
echo "$username"
}
# Function to extract username from 'git@' URL
extract_username_from_git() {
# Remove 'git@' and trailing '.git' from the URL
url_without_protocol=${remote_url#git@}
url_without_protocol=${url_without_protocol%.git}
# Extract the username from the URL (everything between ':' and '/')
username=${url_without_protocol#*:}
username=${username%%/*}
echo "$username"
}
# Check if the remote URL exists and contains 'https://' or 'git@'
if [[ -n "$remote_url" && ( "$remote_url" == https://* || "$remote_url" == git@* ) ]]; then
if [[ "$remote_url" == https://* ]]; then
username=$(extract_username_from_https)
else
username=$(extract_username_from_git)
fi
echo $username
else
echo "Error: Remote 'origin' URL not found or invalid."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment