Why this code says echo is off?

前端 未结 5 1848
灰色年华
灰色年华 2021-02-05 01:46

What is wrong with this code? It says ECHO is off.

@ECHO off
set /p pattern=Enter id:
findstr %pattern% .\\a.txt > result
if %errorlevel%==0 (
se         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 02:26

    As Laurent stated, it's not a problem of the ECHO, it's a problem of your code.

    In batch files, blocks are completely parsed before they are executed.
    While parsing, all percent expansion will be done, so it seems that your variables can't be changed inside a block.

    But for this exists the delayed expansion, the delayed expansion will be evaluated in the moment of execution not while parsing the block.

    It must be enabled, as per default the delayed expansion is disabled.

    @ECHO off
    setlocal EnableDelayedExpansion
    set /p pattern=Enter id:
    findstr %pattern% .\a.txt > result
    if %errorlevel%==0 (
      set var2=  test.txt
      echo(!var1!
    ) else (
      echo error
    )
    del result
    

    I used here the construct echo( instead of echo as this will ensure echoing an empty line even if the variable is empty.

提交回复
热议问题