DXZ
DXZ

Reputation: 495

Why is 'echo on' not effective within an if clause in bat script?

With the following code,

echo off
if 1==1 (
    echo on
    pwd
)

I am expecting the following output,

C:\> echo off
pwd
C:/

but I am getting these.

C:\> echo off
C:/

Why is 'pwd' missing after I turn on echo again in the if clause?

Upvotes: 1

Views: 108

Answers (1)

michael_heath
michael_heath

Reputation: 5372

Full code:

:: Read 1.
echo off

:: Echo off here and will affect Read 2.
@echo

:: Read 2.
if 1==1 (
    echo on
    cd
)

:: Echo on here and will affect Read 3.
@echo

:: Read 3.
cd

3 reads from the interpreter are the focus of this code. @echo is ignored as a actual read as it is just to show the current echo state for testing.

The 1st read is:

echo off

As the script starts as default with echo on, then this read will be displayed with echo on.

The 2nd read is:

if 1==1 (
    echo on
    cd
)

The parentheses causes a multiline code block so it is read as one read. The execution of the echo on will have no effect until the next read. It is too late for the echo on in this code block to affect the current read as it has already been read.

The 3rd read is:

cd

The echo on of the 2nd read will affect the 3rd read and will echo the command cd before executing the command.

Upvotes: 1

Related Questions