Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested if else in BAT file, what am I doing wrong?

Tags:

batch-file

I have the following bat file:

@ECHO off
set ErrorThreshold=
set j=5

IF "%ErrorThreshold%"=="" (
  echo a
) ELSE (
  IF %j% GTR %ErrorThreshold% (
    echo b
  ) ELSE (
    echo c
  )
)

If the ErrorThreshold has no value, the program reports The syntax of the command is incorrect.. If I set a value, everything works.

Can someone help me figure out what's wrong?

like image 405
Dave Q Avatar asked Sep 21 '25 01:09

Dave Q


1 Answers

Logically, the inner IF statement is only executed if the outer IF statement is false. But batch parses complex statements and blocks within parenthteses in one pass. Every line within the parsed block must be valid syntax, even if it does not get executed.

Normal variable expansion occurs before the statements are parsed. So if the variable is not defined, then the inner IF statement becomes IF 5 GTR (, which is invalid syntax.

You could eliminate the syntax error by enclosing both sides in quotes: IF "%j%" GTR "%ErrorThreshold%". But then the comparison will not be numeric.

You could tack on a 0 to both sides instead. This will preserve the numeric comparison and will work as long as the size of the number does not exceed the the limit of a signed 32 bit integer:

IF "%ErrorThreshold%"=="" (
  echo a
) ELSE (
  IF %j%0 GTR %ErrorThreshold%0 (
    echo b
  ) ELSE (
    echo c
  )
)

Another option is to break up the complex statement into multiple statements, and skip the second IF if the variable is not defined by using GOTO:

IF "%ErrorThreshold%"=="" (
  echo a
  goto skip
)
IF %j% GTR %ErrorThreshold% (
  echo b
) ELSE (
  echo c
)
:skip

Yet another option is to use delayed expansion, which occurs after the statement is parsed. The IF statement will see the text !ErrorThreshold! at parse time, and then the value only becomes NULL at execution time. But it is never executed because of the prior IF statement, so all is good.

@ECHO off
setlocal enableDelayedExpansion
set ErrorThreshold=
set j=5

IF "%ErrorThreshold%"=="" (
  echo a
) ELSE (
  IF !j! GTR !ErrorThreshold! (
    echo b
  ) ELSE (
    echo c
  )
)

Note: You could use if not defined ErrorThreshold in place of IF "%ErrorThreshold%"==""

like image 146
dbenham Avatar answered Sep 23 '25 10:09

dbenham