Parenthesis in Windows cmd-script variable values

2019-04-09 18:11发布

问题:

Why gives the following Windows 7 .cmd command script:

set SUN_JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_17

if 3==3 (
 set JAVA_HOME=%SUN_JAVA_HOME%
)
echo ready

The following error message instead of printing "ready"

\Java\jdk1.6.0_17 was unexpected at this time.

The error message disapears, if I remove the "(x86)" in the path name.

回答1:

The problem is the parentheses grouping after the if 3==3 part.

While parsing the set JAVA_HOME=%SUN_JAVA_HOME% command, the interpreter immediately replaces the %SUN_JAVA_HOME% variable and that causes an early match of the closing parenthesis in (386).

This can be avoided if you enable delayed expansion and replace %SUN_JAVA_HOME% with !SUN_JAVA_HOME!:

setlocal enabledelayedexpansion

set SUN_JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_17

if 3==3 (
    set JAVA_HOME=!SUN_JAVA_HOME!
)
echo ready


回答2:

on the command prompt, enter the following commands

C:
CD\
dir /ogen /x

This will show you the 8 character name for Program Files (x86)

Use that name (probably "Progra~2")



回答3:

you have to enclose the set command by double quotes

replace

set SUN_JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_17

by

set SUN_JAVA_HOME="C:\Program Files (x86)\Java\jdk1.6.0_17"

because there's a space in the path



回答4:

I've written about this a while ago (slightly outdated by now).

As an alternative, if you need grouping the commands, then use a subroutine:

if 3==3 call :foo
...
goto :eof
:foo
...
goto :eof


回答5:

Previous answer is ok. I just want clarify it with simple example. It's about detecting Program Files directory for 32-bit application on x86 and x64 systems. There similar problem with "(x86)".

IF DEFINED ProgramFiles(x86) (GOTO x64) ELSE (GOTO x86)
:x64
SET AppDir=%ProgramFiles(x86)%\SomeFolder
GOTO next
:x86
SET AppDir=%ProgramFiles%\SomeFolder

:next
ECHO %AppDir%


标签: windows cmd