Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

shell

I'm writing an automated script.

At some point, I'm calling git clone <repo>. But there is a chance this operation is already done.

How can I call git clone --no-fail so that it ignores if repository exists?

Thanks

like image 783
Augustin Riedinger Avatar asked Apr 08 '16 11:04

Augustin Riedinger


People also ask

How do I clone a git repository already exists?

The git clone creates a copy of a repository that already exists. The git init command is used to generate a new, empty git repository or to reinitialize an existing one. Thus, for generating a git clone , you need a repository created with git init . Then, invoke git clone to copy the data that is included.

How do I clone a git repository to a specific folder?

To clone git repository into a specific folder, you can use -C <path> parameter, e.g. Although it'll still create a whatever folder on top of it, so to clone the content of the repository into current directory, use the following syntax: cd /httpdocs git clone [email protected]:whatever .


3 Answers

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.

like image 68
hek2mgl Avatar answered Oct 16 '22 21:10

hek2mgl


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
like image 32
spannerj Avatar answered Oct 16 '22 21:10

spannerj


It makes the repo latest.

git -C "$TARGET_DIR" pull || git clone https://github.com/<repo>.git "$TARGET_DIR"
like image 12
hiroga Avatar answered Oct 16 '22 21:10

hiroga