Skip to content

Instantly share code, notes, and snippets.

@FredrikM97
Last active June 9, 2026 08:12
Show Gist options
  • Select an option

  • Save FredrikM97/6a8bafeb0bc66944bc90ba0045c3b9d2 to your computer and use it in GitHub Desktop.

Select an option

Save FredrikM97/6a8bafeb0bc66944bc90ba0045c3b9d2 to your computer and use it in GitHub Desktop.
Github switch user
# This is a script for .gitconfig and .ssh/config to manage and switch between user accounts. If first argument to ctx is left empty it is considered default otherwise we append to github.com-*
```
[alias]
ctx = "!f() { \
debug() { \
if [ \"$DEBUG\" = \"1\" ]; then \
echo \"[DEBUG] $*\"; \
fi; \
}; \
\
get_host() { \
echo \"$1\" | sed -E 's#(ssh://)?(git@[^/:]+).*#\\2#'; \
}; \
\
get_scheme() { \
echo \"$1\" | sed -E 's#((ssh://)?git@[^/:]+).*#\\1#' | grep -o '^ssh://'; \
}; \
\
base_host() { \
echo \"$1\" | sed -E 's/-[^.]+//'; \
}; \
\
build_host() { \
HOST=\"$1\"; \
LABEL=\"$2\"; \
BASE=$(base_host \"$HOST\"); \
\
if [ -z \"$LABEL\" ]; then \
echo \"$BASE\"; \
elif echo \"$HOST\" | grep -q -- \"-$LABEL\"; then \
}; \
\
base_host() { \
echo \"$1\" | sed -E 's/-[^.]+//'; \
}; \
\
build_host() { \
HOST=\"$1\"; \
LABEL=\"$2\"; \
BASE=$(base_host \"$HOST\"); \
\
if [ -z \"$LABEL\" ]; then \
echo \"$BASE\"; \
elif echo \"$HOST\" | grep -q -- \"-$LABEL\"; then \
echo \"$BASE\"; \
else \
echo \"${BASE}-${LABEL}\"; \
fi; \
}; \
\
replace_host() { \
URL=\"$1\"; \
FROM=\"$2\"; \
TO=\"$3\"; \
echo \"$URL\" | sed \"s|$FROM|$TO|\"; \
}; \
\
LABEL=\"$1\"; \
EMAIL=\"$2\"; \
NAME=\"$3\"; \
DEBUG=\"$4\"; \
\
CURRENT=$(git remote get-url origin); \
debug \"CURRENT=$CURRENT\"; \
\
FROM=$(get_host \"$CURRENT\"); \
debug \"FROM=$FROM\"; \
\
TO=$(build_host \"$FROM\" \"$LABEL\"); \
debug \"TO=$TO\"; \
\
NEW=$(replace_host \"$CURRENT\" \"$FROM\" \"$TO\"); \
debug \"NEW=$NEW\"; \
\
git remote set-url origin \"$NEW\" && \
git config user.email \"$EMAIL\" && \
git config user.name \"$NAME\" && \
echo \"* Switched to ${LABEL:-default}\" && \
echo \" Email: $EMAIL\" && \
echo \" Remote: $NEW\"; \
}; f"
whoami = "!echo \"Current email: $(git config user.email)\" && git remote -v | head -n1"
whoami = "!echo \"Current email: $(git config user.email)\" && git remote -v | head -n1"
private = "!git ctx private '<private email>' '<private name>'"
default = "!git ctx '' '<work email>' '<work name>'"
```
Apply it on the .ssh/config:
```
Host github.com gist.github.com
HostName github.com
User git
IdentityFile ~/.ssh/keys/id_ed12344
RequestTTY no
IdentitiesOnly yes
Host github.com-private
HostName github.com
User git
IdentityFile ~/.ssh/keys/id_ed12345
RequestTTY no
IdentitiesOnly yes
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment