I’m being driven crazy by a stupidly simple problem that is eating up my time. I just want to append strings separated by comma, but the comma doesn’t get appended. Below is my batch file snippet:
set MissingParams=
set SwitchURL=
set TrustStore=
if 0%SwitchURL%==0 (set MissingParams=SwitchURL)
if 0%TrustStore%==0 (
if not 0%MissingParams%==0 (
set MissingParams=%MissingParams%,
)
set MissingParams=%MissingParams%TrustStore
)
After runnin this script when I echo %MisingParams%, the expected value is SwitchURL,TrustStore but it simply prints
SwitchURLTrustStore.
D:\deleteme>echo %MissingParams%
SwitchURLTrustStore
For debugging, when I introduced some echo statements in the batch file, the results are even more bizzare:
set MissingParams=
if 0%SwitchURL%==0 (set MissingParams=SwitchURL)
if 0%TrustStore%==0 (
if not 0%MissingParams%==0 (
echo MissingParams=%MissingParams%
set MissingParams=%MissingParams%,
echo MissingParams=%MissingParams%
)
set MissingParams=%MissingParams%TrustStore
echo MissingParams=%MissingParams%
)
When I run the above script it prints
MissingParams=SwitchURL
MissingParams=SwitchURL
MissingParams=SwitchURL
And when I echo the value from the command prompt, as before I get SwitchURLTrustStore
D:\deleteme>echo %MissingParams%
SwitchURLTrustStore
Does anyone have any ideas? This is frustrating me to no end.
This is the standard parenthesis/delayedExpansion problem.
The simple rule is %var% are expanded before a parenthesis block is executed(while parsing).
If you need the var-expansion later, you should use the delayed expansion.
Explained in set /?