1

Why does the ECHO command in the following batch always returns ECHO is on.?

@ ECHO ON
FOR /F "usebackq delims=" %%a in (`ECHO`) do (set EchoState=%%a)
@ SET EchoState
@ ECHO OFF
ECHO
@ ECHO for /F "usebackq delims=" %%a in (`ECHO`) do (set EchoState=%%a)
FOR /F "usebackq delims=" %%a in (`ECHO`) do (set EchoState=%%a)
@ SET EchoState

The Output from this batch file is

FOR /F "usebackq delims=" %a in (`ECHO`) do (set EchoState=%a )
    
(set EchoState=ECHO is on. )
EchoState=ECHO is on.
ECHO is off.
FOR /F "usebackq delims=" %a in (`ECHO`) do (set EchoState=%a)
EchoState=ECHO is on.

Line 5 Prints what you would expect ECHO is off. because it is indeed off due to line 4

Why does the ECHO command in this batch file FOR /F Loop always return ECHO is on.?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Peter Nimmo
  • 1,045
  • 2
  • 12
  • 25

1 Answers1

0

for /f runs the specified command in a subshell. Since in the new shell echo is turned on, it'll report "ECHO is on"

This is because the FOR command will start the program in a new sub-shell which removes the outer set of double quotes.

https://ss64.com/nt/for_cmd.html

You can easily see that by spawning a new shell

@echo off
echo
@cmd /c "echo"

The output would be similar to the above

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • Thanks, so does that mean its not possible to identify whether echo is Off or On? – Peter Nimmo Sep 24 '21 at 10:39
  • 1
    @PeterNimmo obviously yes, echo is always on when starting a shell, unless you turn it off by `cmd /Q`. If you want to get the parent shell's echo status then pass it to the subshell – phuclv Sep 24 '21 at 10:50