Search code examples
gitversion-control

Is it possible to use `~` or environment variables in the gitdir option for git repositories?


I want to be able to use environment variables for path expansion in my git settings.

I have a git repo set up with a separate git directory:

git init --separate-git-dir $HOME/bare_repos/.mygitdir

This creates a git repository, with a .git file containing the gitdir field. However the path in the field is fully expanded,

> cat .git
gitdir: C:/Users/MYNAME/bare_repos/.mygitdir
#       ^^^^^^^^^^^^^^^
#      I want this to remain $HOME for portability

Is there a way to have a variable (~ or $HOME etc) in the .git file? For example, changing the .git file to this gives an error:

gitdir: $HOME/bare_repos/.mygitdir

> git status

# fatal: not a git repository: CURRENT/PATH/$HOME/bare_repos/.mygitdir

Note: I understand I can pre-set the GIT_DIR environment variable before calling git commands (GIT_DIR="$HOME/bare_repos/.mygitdir";git status). But I want to be able to skip that manual variable setting in each terminal session.


Solution

  • There is substitution in a .git file created by a git init --separate-git-dir=<git-dir> command.

    No amount of ~, %VAR% or ${VAR} would work.
    Git always precede those by CURRENT/PATH

    The best I came up with was using a relative path:

    cat .git
    gitdir: ../path/to/.mygitdir