Search code examples
batch-filecmd

How to set a variable based on the output of a command in bat?


Here's my problem.

When you call git status --porcelain git returns 0 no matter what the output of the command is.

So the %ERRROREVEL% is of no help to me here.

I need to be able to store the output of git status --porcelain in a variable, and then based on the existence of any character in it realize if there are changes or not.

So basically I need this pseudo-code:

set GitStatusOutput = git status --porcelain
set HasChanges = findstr . in %GitStatusOutput%

But I'm stuck at running this simple need in CMD. I can't change to bash or PowerShell.

I have tried:

    for /f "tokens=*" %%a in ('git -C %%s status --porcelain') do (set GitStatusResult=%%a)
    echo %GitStatusResult%

Not working.

I have tried:

    set HasChangesCommand=git -C %%s status --porcelain | findstr . && echo 1 || echo 0
    echo %HasChangesCommand%

Not working.

How can I do that?

Please note:

I have asked many questions, but with no success.

I have a very very simple need and I'm stuck in for like hours.

I appreciate your time, but I don't need a fancy explanation. I just need a simple answer.


Solution

  • Your for loop assigns each line of the output to the variable, one after the other, so at the end the variable contains the last line of the output. If that happens to be an empty line, the variable will be empty too. But you don't need the for loop in this case. Just filter the output of the command and set the variable according to the result (found at least one char / found no char):

    git -C %%s status --porcelain | findstr . >nul && set "HasChangesCommand=1" || set "HasChangesCommand=0"
    

    Don't forget, you need delayed expansion if you want to use the variable within the same code block / loop.