2013-12-12 98 views
0

由于使用bat/cmd文件中的一些bash.exe调用,我需要将一些变量单引号引起来,其中一些引号是双引号。我正在将一些格式从一种格式转换为另一种格式。是否有可能使它更具普遍性:确定引号的类型,并使它们被双引号给需要它的人,否则将它们单引号?确定蝙蝠变量中的引号(及其类型)

所以我们可以有3种类型的输入参数:

set SOURCE="C:\SRC" 
set SOURCE='C:\SRC' 
set SOURCE=C:\SRC 

而且我需要确定类型的输入,并将其转换在这两种形式:

SOURCE="C:\SRC" 
SOURCE='C:\SRC' 


rem ----------------------------------------------- 
rem  Converting SOURCE in 
rem single quoted format, very important to pass 
rem parameters to bash.exe! 
rem ----------------------------------------------- 
set "SOURCE_CYG=%SOURCE:"='%" 
+0

很难回答,因为您没有显示任何相关的代码 – jeb

+0

单引号变量里面带双引号怎么办?反之亦然。并且,逃脱单\双引号?单引号字符串中的反引号字符串中的单引号字符串?希望是错的,但似乎“普遍”有很多案例。正如jeb所说,需要更多的编码。 –

+0

更新的信息/代码 –

回答

1

:unquote批次子程序,在低于代码结束时,除去任何引用从变量,所以你可以用你想要的任何方式来管理它:

@echo off 
setlocal EnableDelayedExpansion 

set SOURCE="C:\SRC" 
echo Original: %SOURCE% 
call :unquote SOURCE 
echo Double quotes: "%SOURCE%", single quotes: '%SOURCE%' 
echo/ 

set SOURCE='C:\SRC' 
echo Original: %SOURCE% 
call :unquote SOURCE 
echo Double quotes: "%SOURCE%", single quotes: '%SOURCE%' 
echo/ 

set SOURCE=C:\SRC 
echo Original: %SOURCE% 
call :unquote SOURCE 
echo Double quotes: "%SOURCE%", single quotes: '%SOURCE%' 
echo/ 

goto :EOF 

:unquote var 
set quote=" 
if "!%1:~0,1!" equ "!quote!" set %1=!%1:~1,-1! 
if "!%1:~0,1!" equ "'" set %1=!%1:~1,-1! 
exit /B 
0

如果所有的问题是你的示例代码显示的内容,那么这很简单。不要在变量中使用引号。假设没有变量会在其中引用引号,并将所需的引号放在代码中的正确位置。

从批次代码:

set "testVariable=this is a test" 
bash test.sh 

在test.sh

echo $testVariable 
echo "$testVariable" 
echo '$testVariable' 
echo ---------------------- 
for a in $testVariable 
do 
    echo $a 
done 
echo ---------------------- 
for a in "$testVariable" 
do 
    echo $a 
done 
echo ---------------------- 
echo "'"$testVariable"'" 
testVariable="'"$testVariable"'" 
echo $testVariable 
exit 

此输出

this is a test 
this is a test 
$testVariable 
---------------------- 
this 
is 
a 
test 
---------------------- 
this is a test 
---------------------- 
'this is a test' 
'this is a test' 
+0

我在问windows批处理文件,而不是一个。 –

+0

@AntonKochkov:是的,重点不是在变量内部使用引号,而是在需要的地方将它们放在代码中。包含的示例仅仅是值的正确传递/解释。 –

+0

他们是环境变量,所以我需要像现在这样处理它们。 –