Home > Enterprise >  Git environment variables on PowerShell on Windows
Git environment variables on PowerShell on Windows

Time:04-12

The following function was taken from ohmyzsh, and I am rewriting it to work with PowerShell 7.2.2 for educational purposes.

function __git_prompt_git() {
  GIT_OPTIONAL_LOCKS=0 command git "$@"
}

Apparently, PS does not support inline variables like ($foo='bar' func), and ($foo='bar'; func) throws an error at ;. Also, I don't know if Git for Windows reads from $GIT_OPTIONAL_LOCKS or $env:GIT_OPTIONAL_LOCKS.

CodePudding user response:

Environment variables are distinct from normal variables you use in Powershell. The environment is what the env: implicit "PS Drive" lets you access, and this sits alongside several other drive-like namespaces, a few of which are the actual drives like C: and so forth.

PS C:\> get-psdrive

Name           Used (GB)     Free (GB) Provider      Root
----           ---------     --------- --------      ----
Alias                                  Alias
C                 127.73        337.38 FileSystem    C:\
Cert                                   Certificate   \
D                 281.46       2700.96 FileSystem    D:\
Env                                    Environment
Function                               Function
HKCU                                   Registry      HKEY_CURRENT_USER
HKLM                                   Registry      HKEY_LOCAL_MACHINE
Variable                               Variable
WSMan                                  WSMan

And as you might suspect, you can indeed dir (Get-ChildItem) the env: "drive":

PS C:\> dir env:

Name                           Value
----                           -----
ALLUSERSPROFILE                C:\ProgramData
APPDATA                        C:\Users\myname\AppData\Roaming
...

So yes, $GIT_OPTIONAL_LOCKS and $env:GIT_OPTIONAL_LOCKS are indeed completely different. The first is just a variable in the running powershell scope, the second is the environment variable of the same (coincidental) name.

Since environment variables are external you will need to save and restore, for instance like:

$t = $env:GIT_OPTIONAL_LOCKS
$env:GIT_OPTIONAL_LOCKS = 0
git "$@"
$env:GIT_OPTIONAL_LOCKS = $t

This does the right thing if the environment variable does not already exist; $t will be set to $null and setting the environment variable to $null will remove it from the environment.

  • Related