If Else bracket error Help

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
PiotrMP006
Posts: 31
Joined: 08 Sep 2017 06:10

If Else bracket error Help

#1 Post by PiotrMP006 » 09 Dec 2019 06:12

Why this code does not work?

Code: Select all

if exist "D:\Test1" if exist "D:\Test2" (
echo OK
) else (
echo Error
)
pause
This code works but I don't know why this extra brace?

Code: Select all

if exist "D:\Test1" if exist "D:\Test2" (
echo OK
)
) else (
echo Error
)
pause
Please Help

penpen
Expert
Posts: 2009
Joined: 23 Jun 2013 06:15
Location: Germany

Re: If Else bracket error Help

#2 Post by penpen » 09 Dec 2019 07:09

I suspect you want to do that:

Code: Select all

if exist "D:\Test1" (
	if exist "D:\Test2" (
		echo OK
	) else (
		echo Error
	)
) else (
	echo Error
)
Although most probably both of your above code does not work as you intended, it should work fine (from technical viewpoint only).

Your first sample code should:
- do nothing, if "D:\Test1" doesn't exist
- echo "Error" if "D:\Test1" does exist but "D:\Test2" doesn't exist
- echo "OK" if "D:\Test1" and "D:\Test2" do exist

Your second code should:
- echo "OK" and "Error" if "D:\Test1" and "D:\Test2" do exist.
- echo "Error" if "D:\Test1" or "D:\Test2" (or both) don't exist.

The closing parenthesis (')') is a valid command and "else" is allowed to follow any closing parenthesis (which in my eyes probably is a bug, but should date back to xp). The command after the else isn't processed and also if you start with a closing parenthesis it won't start a compound command (aka "block"):

Code: Select all

@echo off
setlocal enableExtensions disableDelayedExpansion
set "test=1"
) else (
	echo Hello %test%!
	set "test=2"
	echo Hello %test%!
)

echo ==== versus ===

set "test=1"
if "1" == "2" (
	echo 
) else (
	echo Hello %test%!
	set "test=2"
	echo Hello %test%!
)

goto :eof
penpen

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: If Else bracket error Help

#3 Post by aGerman » 09 Dec 2019 07:22

The first works as expected since the parentheses belong to the second IF statement. Thus, if the result of the first IF statement is already false, then neither OK nor Error would be displayed. For your second example I get funny results, including both OK and Error at the same time, depending on the conditions.

My assumption is, that you only want to get an OK if both files exist. You may use a helper variable like that:

Code: Select all

set "ok="
if exist "D:\Test1" if exist "D:\Test2" set "ok=1"
if defined ok (
  echo OK
) else (
  echo Error
)
pause
Steffen

Post Reply