windowsgitbatch-filecmdcd

cd with a literal vs a variable leads to git either being discoverable or not


This may be a very basic question, although all responses I could find for it were to "install git" or "be in a git directory." As far as I can see, both of these are resolved already, yet my issue persists. Although the solution could be trivially solved by doing away with having a default behaviour with no input, I'm curious as to what obscure (or basic) behaviour is causing this.

The question [Git via Batch]

Lets say I have a git repo at "C:\RepoBase", amongst possible others, but this is the main repo I want to default to. Without discussing further functionality, the script will either CD to a location provided as input or to the default path if no input is provided, and then proceed to get the name of the current head commit.

:: Go to the repo in question
if [%1]==[] (
    cd C:\RepoBase
) else (
    cd %1
)
:: Get name of current branch
FOR /F "tokens=*" %%g IN (
    'call git rev-parse --abbrev-ref HEAD'
) do (
    SET CurrentBranch=%%g
)

This solution works. If however, I want to have the inconsequential benefit of using the name of the path that I cd'd into later without needing to use a conditional again, even although it would be possible to get the name of the directory after moving into it, I try to set a variable to use as the path. It does CD into the directory fine, but from the same location as the above partial, the below partial's git calls result in a "not recognized." Why?

:: Go to the repo in question
SET PATH=%1
if [%1]==[] (
    SET PATH=C:\RepoBase
) 
cd "%PATH%"
:: Get name of current branch
FOR /F "tokens=*" %%g IN (
    'call git rev-parse --abbrev-ref HEAD'
) do (
    SET CurrentBranch=%%g
)

Solution

  • %PATH% is a system variable that stores directories where Windows looks for executables so that you don't always have to call the full path to everything. You wrote over it, so things that you would normally not need to provide the full path to now require a full path.

    Change your variable name to something else, like REPO_PATH.