I'm just unable to make it work. I used another solution to determine if a received argument contains a certain substring. But it fails whenever I don't enter a third argument. I tried 4/5 methods to check if it exists and to condition the search within the variable but it doesn't seem to work!
set str1=%3
if not "%~3"=="" (
if not x%str1:TEST=%==x%str1% SET additional_config=UNIT_TEST SKIP_WAIT %3
)
How can I avoid evaluating %3 if it doesn't exist to avoid the error?
The code simply should set additional_config if 'TEST' is part of the third argument received. (if there is a third argument)
Your problem is the parsing of if not x%str1:TEST=%
or even if not "%str1:TEST=%"
.
This part is parsed, even if %3
is empty and there comes the problem.
str1
is empty in that case. Percent expansion with search/replace of an empty/undefined variable has unexpected results.
In your case the parser detects at the stage %str1:
, that str1
is undefined and stops the percent expansion.
Therefore, the parser sees
TEST=%==x%str1% SET additional_config=UNIT_TEST SKIP_WAIT %3and it splits it at pairing percent signs:
TEST= %==x% str1 % SET additional_config=UNIT_TEST SKIP_WAIT % 3
The parts in percent signs are invalid or undefined variables
TEST= ... str1 ... 3
At this point the program stops with a syntax error, because the block (inside parenthesis) contains an invalid IF
statement
How to solve it?
One way is to store the value before
set "str1=%~3"
set "contains=%str1:TEST=%"
if not "%~3"=="" (
if not "%contains%" == "%str1%" SET additional_config=UNIT_TEST SKIP_WAIT %3
)
Or even better, use delayed expansion, that doesn't fail this way
@echo off
setlocal EnableDelayedExpansion
set "str1=%~3"
if not "%~3"=="" (
if not "!str1:TEST=!" == "!str1!" SET additional_config=UNIT_TEST SKIP_WAIT %3
)