I'm working on a bash script that uses git to clone all of our git repositories (only the necessary stuff). We have a mixture of master (old projects, and yes we have a task to migrate this) and main as the repo main branches.
I want the script to first try to clone the branch named master and if this fails try to clone the branch named main.
My first try
git clone --depth 1 --branch main "$repoUrl" "$targetFolder"
if [[ "$?" != "0" ]]; then
git clone --depth 1 --branch master "$repoUrl" "$targetFolder"
fi
The first statement tries to clone the master branch of the repository with a url contained within the var repoUrl. And it clones it into a directory contained in the var targetFolder.
Only the latest commit is cloned because of the --depth 1.
So far so good. But i have started using shellcheck a while ago (blog post coming) and it alerted me to slightly better solution.
Turns out it's possible to write it like this:
if ! git clone --depth 1 --branch main "$repoUrl" "$targetFolder"; then
git clone --depth 1 --branch master "$repoUrl" "$targetFolder"
fi
You are able to run the command whose return code you want to check directly in the if clause. I'm doing this here and checking for a return code that says the execution was not successful.
Still some repetition. We could pull this into a function.
gitclone() {
git clone --depth 1 --branch "$1" "$2" "$3"
}
if ! gitclone "main" "$repoUrl" "$targetFolder"; then
gitclone "master" "$repoUrl" "$targetFolder"
fi