In my coding adventures, I often find the need to duplicate a GitHub repository privately. The script provided below gracefully accomplishes this task by following six essential steps:

  • Clone the repo to your local disk.
  • Initiate the repo.
  • Create your own repo with a new name (prepend with ‘better-‘ for clarity).
  • Set the origin URL to your new repo (replace {liveinaus} with your username).
  • Push the changes to the new repo.
  • Done! Enjoy your private repo.
#!/bin/bash

# Get the repository name from the Git URL
get_repository_name() {
  url="$1"

  # Remove the "git@" prefix and the ".git" suffix from the URL
  repository_name="${url#*[@:]}"
  repository_name="${repository_name%.git}"

  # Extract the last component of the URL (repository name)
  repository_name="${repository_name##*/}"
  echo "$repository_name"
}

get_repository_clone_target() {
	local cloneTarget="$1"
	# Remove everything before github.com/
	cloneTarget="${cloneTarget#*github.com/}"

	# Append .git if not exists
	if [[ $cloneTarget != *.git ]]; then
		cloneTarget="$cloneTarget.git"
	fi

	# Prepend [email protected]: if not exists
	if [[ $cloneTarget != [email protected]:* ]]; then
		# Append "[email protected]:" to the URL
		cloneTarget="[email protected]:$cloneTarget"
	fi

	echo "$cloneTarget"
}

github-copy-repo-action() {
	local cloneTarget=$(get_repository_clone_target "$1")
	local newRepoName="${2:-better-$(get_repository_name "$cloneTarget")}"
	local username="${3:-liveinaus}"

	# echo "$cloneTarget"
	# echo "$newRepoName"
	# echo "$username"

	git clone $cloneTarget $newRepoName
	cd $newRepoName
	git init
	gh repo create $newRepoName --private
	git remote set-url origin [email protected]:$username/$newRepoName.git
	git push -u
	echo $'\n\033[1;32m'"✔✔✔  "$'\033[0mFinished copying github repo to $newRepoName\n'
}

github-copy-repo-action "$@"

At the heart of this coding journey lies countless hours of dedication and passion. Every line of code, every debugging session, and every breakthrough is a testament to the love I have for this craft. As you explore the ideas and concepts shared in this blog, I kindly ask you to honour the work involved by quoting the original source. Together, let’s foster a culture of respect, collaboration, and acknowledgement within the coding community. Happy coding!