简体   繁体   English

批量转义函数参数

[英]escape function parameter in batch

I'm working on a DSL that will compile to batch script (for fun...). 我正在开发一种DSL,它将编译为批处理脚本(出于乐趣...)。 I'm trying to make a function call, like that: the DSL defines function with parameter named param1. 我正在尝试进行这样的函数调用:DSL使用名为param1的参数定义了函数。 the batch defines a label with param1=%1. 该批次定义了带有param1 =%1的标签。 the DSL defines a call with some value. DSL定义了具有某些值的呼叫。 the batchs define a call with the value after a space. 批处理定义了一个调用,并在空格后添加了值。

The problem is that if the value has a space, it's defined as two parameters. 问题在于,如果该值具有空格,则将其定义为两个参数。 I can escape spaces with ^, but then if i try to escape a double quote, it gets messed up. 我可以使用^来转义空格,但是如果我尝试使用双引号来转义,它就会变得混乱。

Anyone can help me with the ultimate batch parameter escape? 有人可以帮助我解决最终批处理参数的问题吗?

BTW, its written with MPS, and it's here if you want it: https://github.com/TheAnosmic/MPSBatch BTW,它是用MPS编写的,如果需要,可以在这里: https : //github.com/TheAnosmic/MPSBatch

I think there is no definite reliable way. 我认为没有确定的可靠方法。 The batch parser is really ugly. 批处理解析器真的很丑。 For example if you have a variable with a closing ) the following echo will break: 例如,如果您的变量带有close,则以下回显将中断:

set VAR=Program Files (x86)
echo var=%VAR%.

In some circumstances it helps to use FOR 在某些情况下,使用FOR会有所帮助

@set VAR=a * b "test" c ()
@for /F " delims==" %%V in ("%VAR%") do @echo var=%%V.

Will print 将打印

C:\Users>test.cmd
var=a * b "test" c ().

The simplest solution would be to use double quotes to call your argument. 最简单的解决方案是使用双引号来调用您的参数。

However, if this argument contains some double quotes, it does not work. 但是,如果此参数包含一些双引号,则它将不起作用。 In that case, we can implement a solution based on the solution from eckes: we can do a loop in the function to read all the parameters and copy them into the parameter of the function. 在这种情况下,我们可以基于eckes的解决方案实现一个解决方案:我们可以在函数中执行循环以读取所有参数并将其复制到函数的参数中。

For example, this could look like that: 例如,看起来可能像这样:

@echo off

set var=With "" and a space
call :call_var %var%
goto:EOF

:call_var
set param=
for /F " delims==" %%V in ("%*") do @set param=%param% %%V
REM Test parameter
echo %param%
goto:EOF

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM