Environment variables in .git/config

git, git-config

Solution

I had a similar problem in that I wanted to make my `~/.gitconfig` portable across platforms, so that I could use the same gitconfig on my Macbook and in my Linux VM. I needed `credential.helper` to be different depending on the platform.

I ended up writing a little `generate_gitconfig` script, and add it to my bashrc so that `~/.gitconfig` was generated automatically upon starting each shell session.

Writing your gitconfig via a script gives you more flexibility in that you can set values dynamically based on environment variables, whether certain commands are installed, the hostname of the machine, etc.

Here is my `generate_gitconfig` script, as an example:

#!/bin/bash

cat <<EOF > $HOME/.gitconfig
# This gitconfig was generated via ~/.bin/generate_gitconfig.
# Edit that file, not this one!

[user]
    name = Dave Yarwood
    email = dave.yarwood@gmail.com
[push]
    default = simple
[core]
    autocrlf = input
    editor = nvim
    excludesfile = $HOME/.gitignore_global
[rerere]
    enabled = true
EOF

if [[ "$(uname)" == Darwin ]]; then
  CREDENTIAL_HELPER="osxkeychain"
elif [[ -n "$(which gnome-keyring-daemon)" ]]; then
  CREDENTIAL_HELPER="/usr/share/doc/git/contrib/credential/gnome-keyring/git-credential-gnome-keyring"
fi

if [[ -n "$CREDENTIAL_HELPER" ]]; then
  cat <<EOF >> $HOME/.gitconfig
[credential]
  helper = $CREDENTIAL_HELPER
EOF
fi

Problem

I have a git repo created with the `--serparate-git-dir` option. I often use the same repo form different working trees by specifying `--git-dir` and `--work-tree` as arguments. I have two working trees I switch between frequently so I added a `.git` file in the secondary work tree pointing to the repository directory. However since the repository's `config` file points to the primary working tree, I still have to specify it explicitly, otherwise it uses the primary working tree. I tried setting the value of `worktree` to `$PWD` int the `.git/config` file but this causes the following error: `fatal: Could not chdir to '$PWD': No such file or directory` Is there a way to make `worktree` dynamic?

Original source