Git-Bash is Interpolating Environment Variables

I’m wondering if someone can explain the following strange behavior:

I have a python script using os.environ to pull environment variables for use with pysftp. The variable in question has been called “sftp_wd” and “sftp_wdir” with a value “/etc/<rest of path>” and the effect is the same for both.

>>> import os
>>> os.environ["sftp_wdir"]

This python code in cmd yields the correct value: /etc/...

But when run in git bash the value looks like: <%USERPROFILE%/AppData/Local/Programs/Git>/etc/...

I’m using the same conda environment in both cases and the effect shows up when run in the vscode debugger as well. Additionally if running python with winpty I don’t see this effect. I’ve looked at the documentation on os.environ and for environment variables used by git bash and not found anything to explain this.

printenv also displays the correct value so I’m inclined to believe this is specific to how git bash is initializing python but I can’t seem to pin down what’s actually happening

Edit: In response to @CharlesDuffy it seems this can be replicated with any environment variable and any value starting with “/” example I created an environment variable called random with a value of /var/. Results are as follows:

echo

$ echo $random
/var/

printf

$ printf '%qn' "$random"
/var/

python

$ python
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Ana
conda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['random']
'C:/Program Files/Git/var/'
>>>

Note: The change in the path to the “Git” folder from above is from updating to v2.33.0.2-64bit of Git Bash. The issue is still the same though.

Answer

This is behavior of msys, the Windows-compatibility library that Git Bash is compiled with. The documentation covering this behavior is at https://www.msys2.org/docs/filesystem-paths/

An environment variable is available to turn it off:

  • To turn off automatic path conversion in environment variables entirely, export MSYS2_ENV_CONV_EXCL='*'
  • To turn it off only for the variable named random: export MSYS2_ENV_CONV_EXCL=random