5

I am running input arguments as a command in my dos batch file as I asked in: Run an input parameter as command in dos batch script. That works, however the problem I am having: checking if the input command if it's empty. What I do:

SETLOCAL
set CMD=%*
echo Running command [%CMD%]
IF "%CMD%"=="" (
 echo "Input argument missing: command"
 GOTO :end
)
echo "XXX %CMD%"

And running:

script.bat echo "a b c"

Will output:

Running command [echo "a b c"]
b was unexpected at this time.

This occurs in the IF condition, but why?

How can I check if my input is empty. I know how to check if a string is empty in dos, but for some reason it doesn't work in this combination :(
BTW: If I remove the IF condition it works well, that is: the command is executed correctly.

  • Ed
Community
  • 1
  • 1
edbras
  • 4,145
  • 9
  • 41
  • 78

1 Answers1

3

Test for the absence of parameters first, then assign and process the command:

IF .%1 == . (
 echo "Input argument missing: command"
 GOTO :eof
)

SETLOCAL    
set CMD=%*
echo Running command [%CMD%]
echo "XXX %CMD%"

As to the "Why?", it's because the quotation mark in the value of CMD (the one before a) closes the quotation mark before %CMD%, and so the string appears as "echo "a b c"", and thus b becomes separated from the string, which causes the command processor to fail. (It expects a comparison token, like == or EQU, but not some strange b).

Andriy M
  • 76,112
  • 17
  • 94
  • 154
  • 3
    +1, as you are always correct. But I prefere `if "%~1"==""` as it's mostly safer – jeb Mar 15 '12 at 20:37
  • Thanks, I was thinking to difficult :( – edbras Mar 15 '12 at 20:42
  • @jeb: Thanks. I thought about `"%~1"==""` too, but then it could be misleading if for some reason the first parameter was simply `""` (and the second one was a non-empty value). I mean, we can't be sure if it's all right to specify `""` or not, so I thought I'd go with the `.%1==.` test. – Andriy M Mar 15 '12 at 20:48
  • 1
    Yes, then an empty `""` fails, but strings like `&` or `<` doesn't create syntax errors, but the only realy safe version seems to be the [_REM technic_](http://stackoverflow.com/a/5338799/463115) – jeb Mar 15 '12 at 20:55