Batch: Pipe command output to variable and compare

Viewed 5695

I try to pipe my command output to variables and then compare if those variables have the same value. However it always return both variables have same value(even though it is not). Below is my code:

@echo off
goto main

:main
setlocal

echo 111 | (set /p readvalue= & set readvalue)
echo 123 | (set /p readvaluebash= & set readvaluebash)
if "%readvalue%"=="%readvaluebash%" goto valid
if NOT "%readvalue%"=="%readvaluebash%" goto invalid

:valid
echo yes
pause
goto finish

:invalid
echo no
pause
goto finish


:finish
endlocal

I always get the yes result. Anyone know my mistake here? Thanks in advance!

1 Answers

When you run (same for the other line)

echo 111 | (set /p readvalue= & set readvalue)

you see that the value shown in console as the variable value is 111, so the set /p was able to retrieve the piped data.

The problem is that the pipe operator starts two separate cmd instances: one running the left part (echo) of the pipe and another running the right part (set /p).

As each process has its own environment space and as the set /p is executed in a separate cmd instance, any change to any variable in this new cmd instace will not change the environment of the cmd instance running the batch file.

To store the output of a command in a variable, instead of a pipe you can use a for /f command

for /f "delims=" %%a in ('echo 111') do set "readValue=%%a"
Related