0

When testing for a particular letter in a batch file option, I use code like:

set opts=%2
if not "%opts:t=%" == "%opts%" goto :handle-t-option

However, if %2 is empty, which means opts is empty, then I get a bizarre syntax error, where it seems that the expansion simply doesn't work.

As a workaround, I set opts to include a character not in the set of legal options, just to avoid the syntax error, but thought I'd ask if I'm missing something, or if not, have a question that might help others realize that this is a bizarre corner case.

4
  • What's the problem? Check if %2 is empty and make two different branches in your code depending on the check result. Your syntax error is natural, because "%opts:t=%" makes no sense. Please explain what do you want to achieve. First of all, what information to do you want to pass as %2? Commented 3 hours ago
  • After the set opts instruction, add a new line if defined opts goto somewhereaftertheifnot. Tip: Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. The colon in a goto statement is not required. Commented 3 hours ago
  • It is impossible on Windows to define an environment variable with an empty string. The execution of set opts= results always in a deletion of the environment variable opts on existing at all. See the Microsoft documentation about Environment Variables. The simple solution is inserting below the command line set opts=%2 the command line if not defined opts goto Label to continue the processing of the batch file on no option defined below the line with :Label. Commented 2 hours ago
  • By the way: set opts=%2 is not good in case of a user of the batch file passes for whatever reason "Development & Test 100% (!)" as second argument string to the batch file. That argument string causes an execution of if not ""Developmen & es 100% (!)"" == ""Development & Test 100% (!)"" goto :handle-t-option which results in the error message: & was unexpected at this time. Better would be set "opts=%~2" with syntactically correct if not "Developmen & es 100% (!)" == "Development & Test 100% (!)" goto :handle-t-option and therefore no error message on typical argument strings. Commented 1 hour ago

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.