问题描述:

I'm trying to check few conditions using if else statement on Windows script. Here is the block of code.

if "%1" == "" (

echo empty

) else (

if %1 LSS 1900 (

echo lesser

) else (

if %1 GTR 1900 (

echo greater

)))

I'm trying to echo these statement based on the argument passed. Greater and Lesser conditions are working. But when i dont pass any argument, I get error message on cmd "1900 was unexpected at this time." whereas expected echo is empty.

Please help me on this. If this is a repeated question kindly direct me to the answer. I searched internetand i'm helpless.

网友答案:

That is because %1 then evaluates to an empty string and thus the line reads

if  LSS 1900  (

which is invalid syntax.

The problem here is that everything (because it's conceptually a single statement) is parsed at once, even the parts that are not run at all. One option would be to introduce a variable:

set ARG=0
if not "%1"=="" set "ARG=%1"

if "%1" == "" (
  echo empty
) else if %ARG% LSS 1900  (
  echo lesser
) else if %ARG% GTR 1900 (
  echo greater
)

Note also that the extra blocks are not strictly necessary, so I omitted them here for readability.

相关阅读:
Top