Page 1 of 1

If Else bracket error Help

Posted: 09 Dec 2019 06:12
by PiotrMP006
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

Re: If Else bracket error Help

Posted: 09 Dec 2019 07:09
by penpen
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

Re: If Else bracket error Help

Posted: 09 Dec 2019 07:22
by aGerman
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