Search code examples
if-statementbatch-filecmdpipeio-redirection

What happens with IF command when I pipe to it?


Here is my script:

   @echo off
    echo.|if defined 1 geq 1 echo 1 is geq than 1
    echo.|if defined 2 gtr 100 echo 2 is gtr than 100

    echo.|if 1 gtr gtr 100 echo 1 is gteater than 100
    echo.|if 100 lss gtr 100 echo 100 is gteater and the same time less than 100

the output is :

1 is geq than 1
2 is gtr than 100
1 is gteater than 100
100 is gteater and the same time less than 100

What is going with IF command?


Solution

  • The batch parser concatenates the first tokens after the IF.

    To gain an insight you can use the cmdcmdline variable.

    From a batch file

    @echo off
    echo pipe | if defined 1 geq 1 echo %%cmdcmdline%%
    

    In the output you can see that defined and 1 are concatenated, so this is the cause for the strange results

    C:\Windows\system32\cmd.exe /S /D /c" if defined1 geq 1 echo %cmdcmdline%"

    When you test this from the command line you need to modify the %%cmdcmdline%% to %^cmdcmdline% as the cmd-parser works a bit different with percent expansions.