Volodymyr Bezuglyy
Volodymyr Bezuglyy

Reputation: 16805

"if" with parentheses does not work if there are whitespaces in variable

Why following commands works without any problems:

set PATH=C:\Program Files (x86)\Path\With whitespaces\
if defined APP_HOME set PATH=.;%PATH%

But there is error "\Path\With was unexpected at this time" if I use "if " with parentheses

set PATH=C:\Program Files (x86)\Path\With whitespaces\
if defined APP_HOME ( 
   set PATH=.;%PATH%
)

Upvotes: 3

Views: 358

Answers (1)

dbenham
dbenham

Reputation: 130839

The ) character is sometimes special, sometimes not.

If there is an active (, then the next unquoted, un-escaped ) will close the block.

If there is not an active (, then unquoted, un-escaped ) in a command argument will simply be treated as a literal.

Your PATH variable contains ) which is closing your IF block prematurely. In your case it can be fixed by adding quotes around the assignment.

set PATH=C:\Program Files (x86)\Path\With whitespaces\
if defined APP_HOME ( 
   set "PATH=.;%PATH%"
)

But be careful. Sometimes the PATH contains paths that are already quoted. Enclosing the assignment in quotes can possibly break the assignment if there are already quotes within PATH.

Here is a foolproof way of prepending a value to PATH, regardless what the current definition is. The code assumes delayed expansion is initially disabled.

set PATH=C:\Program Files (x86)\Path\With whitespaces\
if defined temp (
  setlocal enableDelayedExpansion
  for /f "eol=: delims=" %%P in ("!path!") do endlocal & set "PATH=.;%%P"
)

Upvotes: 5

Related Questions