Parenthesis in Windows cmd-script variable values

2019-04-09 18:05发布

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.

标签: windows cmd
5条回答
女痞
2楼-- · 2019-04-09 18:32

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-04-09 18:35

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
查看更多
劳资没心,怎么记你
4楼-- · 2019-04-09 18:37

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楼-- · 2019-04-09 18:48

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%
查看更多
我命由我不由天
6楼-- · 2019-04-09 18:57

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")

查看更多
登录 后发表回答