What's going on in this batch file with the IF,GOTO and VAR

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
taripo
Posts: 228
Joined: 01 Aug 2011 13:48

What's going on in this batch file with the IF,GOTO and VAR

#1 Post by taripo » 06 Nov 2014 07:56

I'm trying to understand what is happening here

I don't have the ASDF environment variable defined, fine.
This is expected.

Code: Select all

C:\Users\username>set | find /i "ASDF" 



This is expected.

Code: Select all

C:\Users\username>IF "%ASDF%"=="" (ECHO A) ELSE ECHO B 
B


This is expected

Code: Select all

C:\Users\username>ECHO "%ASDF%" 
"%ASDF%"



Code: Select all

C:\Users\username>type ffr.bat <ENTER>
@ECHO OFF
IF "%ASDF%"=="" GOTO lab1 ELSE GOTO lab2
:lab1
echo lab1
goto end
:lab2
echo lab2
:end


This is not expected. Why is the IF statement printing the case as if the condition is True?
C:\Users\username>ffr <ENTER>
lab1

And that's when done from a Batch file.


Then I try this test.. I do not see why it prints neither!! Surely either the IF clause is true or the ELSE clause is true!
It doesn't even break and print "A ELSE ECHO B". It just prints nothing!

Code: Select all

C:\Users\username>IF "%ASDF%"=="" ECHO A ELSE ECHO B 



I don't see why this one line IF 4==4 requires parentheses

whereas the IF in the batch file.. The IF in the batch file I notice works
whether I do IF "%ASDF%"=="" (GOTO lab1) ELSE GOTO lab2
or IF "%ASDF%"=="" GOTO lab1 ELSE GOTO lab2


Code: Select all

C:\>IF 4==4 (ECHO A) ELSE ECHO B
A

C:\>IF "4"=="4" ECHO A ELSE ECHO B
A ELSE ECHO B

C:\>IF 4==4 ECHO A ELSE ECHO B
A ELSE ECHO B

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: What's going on in this batch file with the IF,GOTO and

#2 Post by Squashman » 06 Nov 2014 08:08

Read the help for the IF command.

If you want it all on one line you have to put parentheses around the first command you are trying to execute. You have already provided an example of that in your code with the ECHO A but you fail to do it with the GOTO.

Code: Select all

The ELSE clause must occur on the same line as the command after the IF.  For
example:

    IF EXIST filename. (
        del filename.
    ) ELSE (
        echo filename. missing.
    )

The following would NOT work because the del command needs to be terminated
by a newline:

    IF EXIST filename. del filename. ELSE echo filename. missing

Nor would the following work, since the ELSE command must be on the same line
as the end of the IF command:

    IF EXIST filename. del filename.
    ELSE echo filename. missing

The following would work if you want it all on one line:

    IF EXIST filename. (del filename.) ELSE echo filename. missing

Post Reply