Skip to content

Instantly share code, notes, and snippets.

@karlvr
Created November 12, 2020 00:06
Show Gist options
  • Save karlvr/c37679bc3cfc21367872ae125f37bbd9 to your computer and use it in GitHub Desktop.
Save karlvr/c37679bc3cfc21367872ae125f37bbd9 to your computer and use it in GitHub Desktop.
A bash script to search and replace git remotes in multiple git repositories
#!/bin/bash -eu
# Update the git remotes on git working copies contained in the given parent folder.
#
# usage: bulk-update-git-remotes.sh <path containing git repo(s)> <remote search> <remote replace>
#
# e.g. bulk-update-git-remotes.sh ~/git github.com/foo gitlab.com/bar
dryrun=0
while getopts ":n" opt; do
case $opt in
n)
dryrun=1
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
shift $((OPTIND-1))
basedir=${1:-}
search=${2:-}
replace=${3:-}
if [ -z "$basedir" -o -z "$search" -o -z "$replace" ]; then
echo "usage: $0 <basedir> [<search> <replace>]" >&2
exit 1
fi
if [ $dryrun != 0 ]; then
echo "Dry run..." >&2
fi
find "$basedir" -maxdepth 2 -type d -name '.git' -prune | sort | while read git ; do
git=$(dirname "$git")
remotes=$(git -C "$git" remote)
for remote in $remotes ; do
giturl=$(git -C "$git" remote get-url $remote)
if [ -n "$search" ]; then
if [[ $giturl = *$search* ]]; then
newgiturl=${giturl/$search/$replace}
echo "$git: $remote: $giturl => $newgiturl"
if [ $dryrun == 0 ]; then
git -C "$git" remote set-url $remote "$newgiturl" "$giturl"
fi
fi
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment