Shell: don't crash if git clone if folder already exists

I am writing an automated script.

At some point I call git clone <repo> . But there is a chance that this operation has already been completed.

How can I call git clone --no-fail so that it ignores the existence of the repository?

thanks

+6
source share
4 answers

The most sustainable solution would be to simply let it fail.

You can do something like:

 if [ ! -d "$FOLDER" ] ; then git clone "$URL" "$FOLDER" fi 

but it will be vulnerable to race conditions.

+8
source

git clone $url || true git clone $url || true will cause shell startup with set -e fail with a git clone error.

If this is not what you want, then the proposed solutions with explicit testing for an existing target directory should work.

The only problem with them is that you will need to mimic the Git approach to determine its name.

Something like this should work:

 url=git://host/path/name.git last=${url##*/} bare=${last%%.git} test -e "$bare" || git clone "$url" 

These " ## and %% " tricks are standard features of the "parameter extension" POSIX shell rules .

+1
source

It's a bit late for the party, but I am doing something similar, but I want the repo to be updated if it already exists, so to expand on this answer if the repo already existed, you could pull it to make sure it is updated.

 if [ ! -d "$FOLDER" ] ; then git clone "$URL" "$FOLDER" else cd "$FOLDER" git pull "$URL" fi 
+1
source

You do not tell us why it may already be there, or any context.

I would really like to add [ -e $folder ] && rm -rf $folder (making sure $folder is normal) before git clone , because I would not want my software to use any old folder, which is just accidentally lies there, who knows what condition ...

0
source

All Articles