~cyborg/php-blog

ref: fe42f82d527a47eb449983f900fbba566e1e8fd0 php-blog/posts/028-how-to-clone-all-github-repositories.md -rw-r--r-- 2.1 KiB
fe42f82dcyborg update git links 7 months ago

#Use a Bash Script!

If you're like me and use a lot of different devices (and sometimes decide to just wipe your device and start with a new OS), you probably know the pain of cloning all your old code repositories down to your local file system.

If you're using GitHub, you can easily clone all of your code back down in just seconds. First, create a bash script - I do so by opening a new file in gedit, but you can use nano, vim, or something else:

gedit clone_github_repos.sh

Next, paste in the following information. Note that you can replace the word users in the first line with orgs and type an organization's name instead of a user's name.

CNTX={users}; NAME={YOUR-USERNAME}; PAGE=1
curl "https://api.github.com/$CNTX/$NAME/repos?page=$PAGE&per_page=100" |
  grep -e 'git_url*' |
  cut -d \" -f 4 |
  xargs -L1 git clone

Finally, save the bash script and make it executable.

chmod a+x clone_github_repos.sh

Now you can run the script and should see the cloning process begin.

./clone_github_repos.sh

#Moving Repositories to a New Host

Now that you have all of your code repositories cloned to your local computer, you may want to change the remote host (e.g. moving from GitHub to GitLab). To do this, let's create another bash script:

gedit change_remote_urls.sh

Past the following information and be sure to change the URL information to whichever host you are moving to. For this example, I am looping through all of my cloned GitHub directories and changing them to Sourcehut (e.g. <YOUR_NEW_REMOTE_URL> -> git@git.sr.ht:~cyborg).

# List all sub-directories in the current directory
for dir in */
do
    # Remove the trailing "/"
    dir=${dir%*/}
    # Enter sub-directory
    cd $dir
    # Change remote Git URL
    git remote set-url origin <YOUR_NEW_REMOTE_URL>/"${dir##*/}"
    # Push code to new remote
    git push
    # Go back to main directory
    cd ..
done

Finally, save the bash script and make it executable.

chmod a+x change_remote_urls.sh

Now you can run the script and should see the cloning process begin.

./change_remote_urls.sh