bartek
bartek

Reputation: 3021

how to use git from another directory?

Assume there is folder structure like:

repos
    /repo1  <-- here is git repository

I do:

cd repos

And how can I now use repository in /repo1 still being in repos directory? I don't want to do

cd repo1
git status (...)
git commit (...)
...

but something like:

git --git-dir=repo1 (...)

or

git --work-tree=repo1 (...)

I want to do ALL git commands in that style, event git init. What's the correct approach?

Upvotes: 13

Views: 5328

Answers (3)

Jim Stewart
Jim Stewart

Reputation: 17323

You can combine --git-dir and --work-tree to operate on a repo outside the current directory:

git --git-dir=/some/other/dir/.git --work-tree=/some/other/dir status

You can also set GIT_DIR as @opqdonut mentioned, but you'll also have to set GIT_WORK_TREE. Note that GIT_DIR is the path to the .git directory in the target repository, and GIT_WORK_TREE is the target repository itself.

This is all really convenient, but here's a shell function that will make your life easier:

function git-dir() {
    dir=$1
    shift
    git --git-dir="$dir/.git" --work-tree="$dir" $*
}

That will work in Bash or Zsh (and probably other Bourne-derived shells). Put it in your ~/.bashrc or ~/.zshrc or wherever is appropriate for your environment.

Then you can just do this:

git-dir /some/other/dir status

Where status is any Git command. It works with other arguments as well, which are passed directly to the git command:

git-dir /some/other/dir remote -v

Upvotes: 3

Stefan van den Akker
Stefan van den Akker

Reputation: 6999

Git has the -C <path> option (like tar -C <path>) that changes the working directory for Git to path and then executes the command in that directory. Example run:

$ mkdir gitrepo
$ git -C gitrepo init
Initialized empty Git repository in /home/foo/gitrepo/.git/

man git:

-C <path>

Run as if git was started in <path> instead of the current working directory. When multiple -C options are given, each subsequent non-absolute -C <path> is interpreted relative to the preceding -C <path>.

This option affects options that expect path name like --git-dir and --work-tree in that their interpretations of the path names would be made relative to the working directory caused by the -C option. For example the following invocations are equivalent:

git --git-dir=a.git --work-tree=b -C c status
git --git-dir=c/a.git --work-tree=c/b status

My version of Git is 2.16.1.

Upvotes: 13

opqdonut
opqdonut

Reputation: 5159

You can set the environment variable $GIT_DIR. Look it up.

Upvotes: 4

Related Questions