How to use git from another directory?

Suppose there is a folder structure like:

repos /repo1 <-- here is git repository 

I do:

 cd repos 

And how can I now use the repository in /repo1 located in the repos directory? I do not want to do

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

but something like:

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

or

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

I want to execute ALL git commands in this style, the git init event. What is the right approach?

+4
source share
3 answers

You can set the environment variable $GIT_DIR . Take a look.

+4
source

Git has a parameter -C <path> (for example, tar -C <path> ), which changes the working directory for Git to path , and then executes a command in that directory. Execution Example:

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

man git :

-C <path>

Run as if Git was running in <path> instead of the current working directory. When multiple -C parameters are specified, each subsequent non-absolute -C <path> interpreted relative to the previous -C <path> .

This option affects options that expect a path name, such as --git-dir and --work-tree , in that their interpretation of the path names will be made relative to the working directory invoked by the -C option. For example, the following calls 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.

+1
source

You can combine --git-dir and --work-tree to work with repos 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, but you also need 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.

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

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

This will work in Bash or Zsh (and possibly other shells derived from Bourne). Put it in ~/.bashrc or ~/.zshrc or where appropriate for your environment.

Then you can simply do this:

 git-dir /some/other/dir status 

Where status is any Git command. It also works with other arguments that are passed directly to the git command:

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

Source: https://habr.com/ru/post/1446635/


All Articles