Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Clone a git repo if it does not exist, or pull into it if it does exist
# We do it this way so that we can abstract if from just git later on
if [ ! -d $LOCALREPO_VC_DIR ]
git pull $REPOSRC
# End
Copy link

HaleTom commented Sep 28, 2016

Suggest quoting your variables in case of whitespace for robustness!

Copy link

YannDubs commented Dec 12, 2017

I know it's very old but for those interested in a one liner, I would suggest using: git clone <REPOSRC> || (cd <LOCALREPO> ; git pull).

Copy link

@YannDubs, I like your oneliner. It works great!

btw: Is there a way to "swallow" the error message generated by git clone <REPOSRC> to make the output less confusing in case a repo exists?

Copy link


git clone "$REPOSRC" "$LOCALREPO" 2> /dev/null || (cd "$LOCALREPO" ; git pull)

Copy link

git clone "$REPOSRC" "$LOCALREPO" 2> /dev/null || git -C "$LOCALREPO" pull

Copy link

cben commented Mar 25, 2020

/dev/null would hide error messages in first clone, so the full if conditional is safer.
Can always use ; to compress shell code into a one-liner... 😉

Could also do the pull unconditionally, mildly less efficient but condenses to:

(cd $LOCALREPO; git pull $REPOSRC)

The parens around (cd ...; git pull ...) are not needed when it's a standalone script like here but good in a larger context — cd done in a sub-shell won't affect the rest of the script.

P.S. A futher tweak: testing existance -e $LOCALREPO_VC_DIR rather than requiring it to be a directory -d is slightly more generic for cases when the clone was created by other means — it's possible for .git to be a text file with content gitdir: ..., as set up by git submodule, git worktree and maybe others...

Copy link

I made this script, a "little bit" more complex but which fulfilled my specific needs:

Copy link

git clone "$REPOSRC" "$LOCALREPO" 2> /dev/null || (cd "$LOCALREPO" ; git pull)

Thank you. 👍

Copy link

No need to cd into the directory to pull from it. git -C "$LOCALREPO" pull

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment