Batch scripting: If statement

S

Slickuser

When I execute this batch script with two prompts set to N.
What am I doing wrong that it's entering the second "if statement"?

Result:
Enter (Y/N) N
Enter2 (Y/N) N
Msg 1
C_PATH exist
Should not be here!





@SET OVERWRITE=N
@SET /P OVERWRITE="Enter (Y/N) "
@SET C_PATH=C:\Windows

:: BEGIN
@IF "%OVERWRITE%" == "Y" (
@ECHO Hey %USERNAME%
@ECHO Got IN overwrite

@IF EXIST %C_PATH% (
@ECHO %C_PATH% exist
)

@IF "A" == "A" (
@ECHO Hello!!
)

@ECHO Should not display this message!
)


@SET COMPILE=N
@SET C_OVERWRITE=N
@SET /P COMPILE="Enter2 (Y/N) "

@IF "%COMPILE%" == "Y" (
@ECHO Hey2 %USERNAME%

:: Check if directory is already exist
@IF EXIST %C_PATH% (
@ECHO %C_PATH% exist
@SET /P C_OVERWRITE="Overwrite %C_PATH% [Y/N] "
)

:: Ask for overwrite
@IF "%C_OVERWRITE%" == "Y" (
@ECHO C overwrite
)

@ECHO Msg 1
@IF EXIST %C_PATH% (
@ECHO C_PATH exist
)
@ECHO Should not be here!
)
 
V

VanguardLH

Slickuser said:
When I execute this batch script with two prompts set to N.
What am I doing wrong that it's entering the second "if statement"?

...
@SET COMPILE=N
@SET C_OVERWRITE=N
@SET /P COMPILE="Enter2 (Y/N) "

@IF "%COMPILE%" == "Y" (
...
:: Check if directory is already exist
...
:: Ask for overwrite
)

You are putting labels *inside* the scope of the IF's code block. You
can't jump to a label inside an IF block. You cannot have labels on the
same [logical] line as a command. Labels must start at the first
non-whitespace character on a line.

:label
:: invalid label as comment
:label
:: invalid label as comment

are legal but:

IF <criteria> <cmd> :: invalid label as comment

is not legal. The label did not *start* as the first non-whitespace
character on the line.

Although :: is a label (to an id of ":" which makes in unaddressed by
GOTO) which can sometimes be used in place of a REM, it is *not* the
same as REM. The :: label lines used as comments end up being in the
SAME line as the IF command. The "line" delimiter for the IF doesn't
end until the closing parenthesis but you are inserting labels in that
same line which is not allowed.

If you remove the :: lines, does the code run as expected?

Don't use labels inside code blocks.
http://www.robvanderwoude.com/comments.php

Because of my tendency to document my code as I write it, and because of
the problems that using the invalid :: label delimiter can cause, I gave
up on using :: as a comment and just use the standard REM command.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top