带有空格和圆括号的批处理文件变量

Hoo*_*oob 4 windows variables escaping batch-file

我读过不同的方法很多线程来获取Windows批处理文件分析器妥善处理有空格,括号和其他特殊字符变量,但没有建议似乎能解决我遇到的问题.

这是脚本(在尝试任何变通方法之前),其目标是根据为variable01和variable02找到的值设置variable03的值:

set variable01="C:\Program Files (x86)\SomeProgram\Subfolder"
set variable02="${macro}"

set variable01=%variable01:"=%
set variable02=%variable02:"=%

set variable03=""

if %variable02:~0,1%==$ (
   if %variable01:~0,1%==$ (
      set variable03=%variable03:"=%
   ) else (
      set variable03=-o '%variable01%'
   )
)
Run Code Online (Sandbox Code Playgroud)

... variable01和variable02的值事先不知道 - 它们是由之前运行脚本另一个程序取代,因此,上述脚本示出设置variable01和variable02值的那个替换已被制成之后的示例.

运行此脚本时出现的错误是:

\SomeProgram\Subfolder' was unexpected at this time.
Run Code Online (Sandbox Code Playgroud)

...对应于上述脚本中的最后一个"set"行.我假设这个错误是由于variable01的值括起来的.

如果我将该行更改为:

set "variable03=-o '%variable01%'"
Run Code Online (Sandbox Code Playgroud)

...然后我收到此错误:

Files was unexpected at this time.
Run Code Online (Sandbox Code Playgroud)

...这似乎表明它正在尝试对variable01中的空格进行标记,并且解析器仍然不满意.

如果我然后在脚本的顶部添加此行:

 setlocal enableextensions enableDelayedExpansion
Run Code Online (Sandbox Code Playgroud)

...并将%variable01%更改为!variable01!,我仍然得到相同的错误.

显然,我不明白批处理文件解析器需要满足我的要求,即variable03的值具有以下值:

-o 'C:\Program Files (x86)\SomeProgram\Subfolder'
Run Code Online (Sandbox Code Playgroud)

...有什么建议?

jeb*_*jeb 7

正如Nate所写,这种情况下的问题是括号,但完整的代码仍然不稳定.

使用延迟扩展总是更好,因为这对任何特殊字符都是安全的.
你应该使用扩展语法SET set "variable=content"用引号括起整个表达式,然后它几乎是安全的,并且引号不会添加到内容中.
而且您以后不需要删除引号.

这应该适用于var1和var2中的任何内容

setlocal EnableDelayedExpansion
set "variable01=C:\Program Files (x86)\SomeProgram\Subfolder"
set "variable02=${macro}"

set "variable03="

if "!variable02:~0,1!"=="$" (
   if "!variable01:~0,1!"=="$" (
      rem
   ) else (
      set "variable03=-o '!variable01!'"
   )
)
echo(!variable03!
Run Code Online (Sandbox Code Playgroud)


Nat*_*man 3

问题在于variable01s 值中的括号。由于它是在if条件下扩展的,因此这些括号被解释为流量控制。通过始终将其放在双引号中来修复。

set variable01="C:\Program Files (x86)\SomeProgram\Subfolder"
set variable02="${macro}"

set variable01=%variable01:"=%
set variable02=%variable02:"=%

set variable03=""

if "%variable02:~0,1%"=="$" (
   if "%variable01:~0,1%"=="$" (
      set variable03=%variable03:"=%
   ) else (
      call :set3 "%variable01%"
   )
)
goto :eof

REM If it is important to have single quotes instead of double then
REM I found I had to call a subroutine.  Otherwise the set could be
REM left up in the else.
:set3
set variable03=-o '%~1'
goto :eof
Run Code Online (Sandbox Code Playgroud)