Created
July 6, 2023 00:16
-
-
Save ikwyl6/61b79a689d71581774358027cf7cc3e6 to your computer and use it in GitHub Desktop.
bash script for github to change all https clone/repo urls to ssh urls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Script git-chg-to-ssh.sh | |
# Uploaded to gist github | |
# | |
# By [email protected] | |
# | |
# Change all https github clone addresses to ssh | |
# Use DEBUG=[1|2] before command to see some debug output | |
# Use PROCEED=1 to actually make the 'set-url' change | |
# | |
# Example: DEBUG=1 ./git-chg-to-ssh.sh /home/user/repos | |
# PROCEED=1 ./git-chg-to-ssh.sh /home/user/repos | |
dest="$1" # root folder where you clones or github repositories live | |
user="" # your github username | |
website="https://github.com" # using github for main website | |
backup_file="$HOME/dev/github_links.txt" # change this to whatever you like | |
if [[ "$dest" == "" ]]; then | |
echo "Provide root directory of git dirs"; | |
exit 1; | |
fi | |
if [[ ! -d "$dest" ]]; then | |
echo "$dest is not a directory" | |
exit 1 | |
fi | |
# Backup your existing github 'get-url' before you change them | |
backup_github_link() { | |
echo "$1" >> $backup_file | |
} | |
while read dir; do | |
cd "$dir"; | |
if [[ DEBUG -ge 2 ]]; then echo "dir: $dir" | |
fi | |
if [[ -d "$dir/.git" ]]; then | |
git fetch | |
# Read in all the remotes for a repository into array | |
read -r -d '' -a remote_arr < <(git remote) | |
repo_name_long="$(git rev-parse --show-toplevel)" | |
repo_name=$(basename "$repo_name_long") | |
echo "$repo_name" | |
for remote in "${remote_arr[@]}"; do | |
if [[ DEBUG -ge 1 ]]; then echo "remote: $remote" | |
fi | |
url=$(git remote get-url "$remote") | |
backup_github_link $url | |
if [[ $url == https* ]]; then | |
# https://stackoverflow.com/questions/1898553/return-a-regex-match-in-a-bash-script-instead-of-replacing-it | |
if [[ "$url" =~ $website/([a-zA-Z0-9_]+)/ ]]; then | |
username="${BASH_REMATCH[1]}" | |
if [[ DEBUG -ge 1 ]]; then echo " username: $username" | |
fi | |
fi | |
echo " Updating https to ssh git..." | |
new_url="git remote set-url $remote [email protected]:$username/$repo_name" | |
if [[ DEBUG -ge 1 ]]; then echo -e " $dir\n old: $url\n new: $new_url" | |
fi | |
if [[ PROCEED -eq 1 ]]; then | |
git remote set-url $remote [email protected]:$username/$repo_name | |
fi | |
fi | |
done | |
fi | |
done < <(find "$dest/" -maxdepth 1 -type d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment