Home > database >  Prevent or work around Git for Windows updater changing git binary precedence in PATH
Prevent or work around Git for Windows updater changing git binary precedence in PATH

Time:01-12

I have PowerShell scripts on my machine which call git, i.e. Git for Windows. I also have Cygwin installed, which has a git binary in the main bin folder which it adds to the PATH.

When I'm calling git from these scripts, I want them to use the normal Git for Windows binary. (The cygwin binary won't work, it thinks unchanged files are changed when running "git status --porcelain," I suspect owing to something different about line endings in its global config. That's beside the point.) As a result, I set my PATH to have the Git for Windows binary folder appear before the Cygwin bin folder. This is perfect, the correct binary gets called by scripts and Cygwin can continue existing unperturbed.

The problem is that every time Git for Windows auto-updates, it edits the PATH to remove its entry, then re-add its entry, effectively moving its entry to the end - behind Cygwin in precedence. My script fails a few times until I remember I need to go edit the PATH again.

Is there a way to get the Git for Windows updater to leave the PATH alone, a better way to get the PowerShell scripts to use the correct git binary (without hardcoding the path, the script must work on all developers' machines), or some other workaround?

CodePudding user response:

This is more of a workaround using a PowerShell profile, but if you add:

$env:PATH = 'C:\Path\To\Git\For\Windows\bin;'   $env:PATH

to one of your $profile locations, this will effectively guarantee that the Git for Windows binaries always come before cygwin does. Note that this doesn't workaround the issue for processes launched outside of PowerShell or PowerShell sessions started with -NoProfile.

You can see your profile locations by checking the following variables:

$profile.AllUsersAllHosts
$profile.AllUsersCurrentHost
$profile.CurrentUserAllHosts
$profile.CurrentUserCurrentHost

Alternatively, you could bake the $env:PATH mutation into your scripts which need it, if you can't or don't want to use the profile approach. The point is that modifying the PATH variable effectively sidesteps this issue.

CodePudding user response:

Use Get-Command to resolve both binaries, then use Set-Alias to hide whichever one takes precedence behind the one you need:

$gitForWindows = Get-Command git -All |Where-Object Source -notlike *cygwin*
Set-Alias git -Definition $gitForWindows
  •  Tags:  
  • Related