DEAR PEOPLE FROM THE FUTURE: Here's what we've figured out so far...

Welcome! This is a Q&A website for computer programmers and users alike, focused on helping fellow programmers and users. Read more

What are you stuck on? Ask a question and hopefully somebody will be able to help you out!
+1 vote

Is it possible to checkout a git repository without cd-ing into the directory first?

$ pwd

$ git checkout dev </home/wonk/repo/path>    # <-- like this?

Do you mean you would like the repo to be created in /home/wonk directly, without first changing into the directory?

git checkout $url /home/wonk/repo should work fine, or maybe I misunderstand the question.


I'm in directory A and want to checkout a specific branch in directory B without cd into B.
What I do now:

cd B                    # enter in B
git checkout $branch    # change branch
cd A                    # go back to A

What I would like to do:

git checkout $branch $repo_path # change branch in $repo_path without changing directories

The command below will re-download the repo again so it's not a cached checkout, but is probably close to what you wanted in that there's no need to change between directories:

git -C /path/to/parent/of/B clone $repo-url B -b $branch

The -C flag allows specifying the path to clone into. Adjust the path to point to B if you want the folder to be inside B rather than the top-level being B.

1 Answer

0 votes

i believe that the short answer is "no" - git is not going to act on a repo without being below it's git root - in fact, even then, the latest version of git will refuse to do anything, unless the repo is owned by the same user, or is added to a whitelist

the obvious solution is already posted by the OP

cd $repo ; git checkout $branch ; cd -

... so i assume that there is some reason to literally avoid changing directories - a variation on that would be to do the work in a sub-shell

$ repo=/home/wonk/repo/path
$ branch=dev
$ pwd
$ ( cd $repo ; git checkout $branch )
$ pwd
Contributions licensed under CC0