4

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!

2
  • 1
    Protect your subroutines; make sure there's an unconditional goto before each entry point. Also, troubleshoot by trying to echo the values of the variables. Commented Sep 20, 2017 at 13:54
  • try echo 111, next line set /p readvalue= & set readvalue, next line echo 123, next line set /p readvaluebash= & set readvaluebash, or to say it easy line after line not echo 123 | (set....) Commented Sep 20, 2017 at 13:58

1 Answer 1

10

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"
4
  • Ah I see! So that means there is no way I can perform the "%readvalue%"=="%readvaluebash%" in one batch file? Probably the best workaround is to save into .txt first I guess? Commented Sep 20, 2017 at 14:15
  • 4
    @GregorIsack, That means you can not use a pipe to change a variable and see the change inside the current batch file. If you need to store in a variable the output of a command use a for /f command
    – MC ND
    Commented Sep 20, 2017 at 14:17
  • Learned a new thing! Thank you so much! Commented Sep 20, 2017 at 14:22
  • How to capture the%ERRORLEVEL% from echo 111 as well? Commented Aug 11, 2022 at 17:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.