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

The most stable solution would be to simply let it fail and print the error message. If you think that's too ugly for your scenario, you may redirect it to /dev/null:

folder="foo"
if ! git clone "${url}" "${folder}" 2>/dev/null && [ -d "${folder}" ] ; then
    echo "Clone failed because the folder ${folder} exists"
fi

Otherwise you can do something like this:

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

but that would be vulnerable to race conditions.


A bit late to the party but I'm doing something similar but I want to ensure the repo is up to date if it already exists so to expand on the above answer if the repo already existed you could then pull to ensure it's up to date.

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

git clone $url || true would make shell runing with set -e not fail on git clone having had failed.

If this is not what you want then the suggested solutions with explicit testing for the target directory being already there should work.

The only problem with them is that you'd need to simulate Git's approach to figuring out its name.

Something like this should work:

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

Those "tricks" with ## and %% are standard featues of the "parameter expansion" rules of POSIX shells.

Tags:

Shell

Git