Skip to content

Instantly share code, notes, and snippets.

@AshCoolman
Created November 5, 2025 09:09
Show Gist options
  • Select an option

  • Save AshCoolman/2e9e54bb0502b6d535a3cc3f50e0463a to your computer and use it in GitHub Desktop.

Select an option

Save AshCoolman/2e9e54bb0502b6d535a3cc3f50e0463a to your computer and use it in GitHub Desktop.
Setup github SSH
#!/usr/bin/env bash
# setup-github-ssh.sh — macOS/Ubuntu. Creates (if needed) an ed25519 key, loads it, and registers it with GitHub via gh (if available).
set -euo pipefail
KEY="${HOME}/.ssh/id_ed25519"
PUB="${KEY}.pub"
EMAIL="${GIT_EMAIL:-}" # optional: export GIT_EMAIL="[email protected]" to tag the key comment
TITLE="${HOSTNAME:-$(hostname)} $(date +%Y-%m-%d)"
OS="$(uname -s || true)"
mkdir -p "${HOME}/.ssh"
chmod 700 "${HOME}/.ssh"
# 1) Ensure ssh-agent + config
pgrep -u "$USER" ssh-agent >/dev/null 2>&1 || eval "$(ssh-agent -s)" >/dev/null
grep -q "^Host github.com$" "${HOME}/.ssh/config" 2>/dev/null || cat >> "${HOME}/.ssh/config" <<'CFG'
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
AddKeysToAgent yes
CFG
# macOS keychain (safe to repeat)
if [[ "${OS}" == "Darwin" ]]; then
grep -q "UseKeychain yes" "${HOME}/.ssh/config" 2>/dev/null || {
printf "\nHost *\n UseKeychain yes\n" >> "${HOME}/.ssh/config"
}
fi
# 2) Create key if missing (ed25519). Prompts for passphrase (press Enter for none).
if [[ ! -f "${KEY}" ]]; then
COMMENT="${EMAIL:-${USER}@${TITLE}}"
ssh-keygen -t ed25519 -C "${COMMENT}" -f "${KEY}"
chmod 600 "${KEY}"
fi
# 3) Add to agent
ssh-add -l >/dev/null 2>&1 || true
ssh-add "${KEY}" >/dev/null
# 4) Register with GitHub
if command -v gh >/dev/null 2>&1; then
# Ensure gh auth (device flow if needed)
if ! gh auth status >/dev/null 2>&1; then
gh auth login -s admin:public_key -w
fi
# Add public key (idempotent: compare fingerprint first)
FINGERPRINT_LOCAL="$(ssh-keygen -lf "${PUB}" | awk '{print $2}')"
if ! gh ssh-key list --json key,fingerprint --jq '.[].fingerprint' 2>/dev/null | grep -q "${FINGERPRINT_LOCAL}"; then
gh ssh-key add "${PUB}" -t "${TITLE}"
fi
else
echo "gh not found → manual add:"
if [[ "${OS}" == "Darwin" ]] && command -v pbcopy >/dev/null; then
pbcopy < "${PUB}"
echo " Public key copied to clipboard. Add it at: https://github.com/settings/keys"
elif command -v xclip >/dev/null; then
xclip -selection clipboard < "${PUB}"
echo " Public key copied to clipboard. Add it at: https://github.com/settings/keys"
else
echo " Paste this at https://github.com/settings/keys:"
echo " -----8<-----"
cat "${PUB}"
echo " ----->8-----"
fi
fi
# 5) Verify
ssh -o StrictHostKeyChecking=accept-new -T [email protected] || true
echo "DONE. If you see 'Hi <user>! You've successfully authenticated…' above, SSH is working."
@AshCoolman
Copy link
Author

Usage

curl -fsSL <link to raw gist> | bash

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