2014-03-03 117 views
4

批处理文件变量名称有什么限制,为什么?CMD变量名称限制?

我注意到我无法回显名称为:)的变量。

h:\uprof>set :)=123 

h:\uprof>set :) 
:)=123 

h:\uprof>echo %:)% 
%:)% 

从一个批处理文件显然:)输出,而不是%:)%。这个问题显然不适用于set命令,因为该变量和它的值出现在set的输出中。

奇怪的是,当分开时 - :) - 反转 - ): - 当用作变量名称时,所有输出它们的给定值。

回答

4

:是变量扩展的字符串操作特殊字符。例如:

%var:~0,1% 

因此,如果有任何变量名如下:,它会尝试执行字符串操作和失败。这允许冒号字符本身或者什么都没有追踪它。

有关扩展变量名称的规则:变量名称不能包含:后面跟着任何字符,否则变量扩展将失败。

set /?


set :)=123 
set a)=123 
set :a=123 
set :=123 
set)=123 
echo %:)% 
echo %a)% 
echo %:a% 
echo %:% 
echo %)% 

输出:

%:)% 
123 
%:a% 
123 
123 
+0

当然,完全滑了我的脑海。谢谢。 – unclemeat

+0

+1,不完全是整个故事,但接近;)请参阅[我的回答](http://stackoverflow.com/a/22159812/1012053) – dbenham

4

是永远不能出现在用户定义的批处理环境变量名是=唯一的字符。 SET语句将在第一次出现=时终止一个变量名称,之后的所有内容都将成为该值的一部分。

指定包含:的变量名很简单,但通常情况下,除特定情况外,不能展开该值。

当扩展名被启用(默认行为)

结肠是搜索的一部分/替换和子串扩展语法,这与含有在名称结肠变量膨胀干涉。

有一个例外 - 如果:显示为名称中的最后一个字符,那么该变量可以扩展得很好,但是不能对该值执行搜索和替换或子字符串扩展操作。

当扩展是禁用

查找/替换和子扩张是不可用的,所以没有什么从工作得很好停止含冒号变量的扩张。

@echo off 
setlocal enableExtensions 

set "test:=[value of test:]" 
set "test:more=[value of test:more]" 
set "test" 

echo(
echo With extensions enabled 
echo ------------------------- 
echo %%test:%%    = %test:% 
echo %%test::test=replace%% = %test::test=replace% 
echo %%test::~0,4%%   = %test::~0,4% 
echo %%test:more%%   = %test:more% 

setlocal disableExtensions 
echo(
echo With extensions disabled 
echo ------------------------- 
echo %%test:%%  = %test:% 
echo %%test:more%% = %test:more% 

--OUTPUT--

test:=[value of test:] 
test:more=[value of test:more] 

With extensions enabled 
------------------------- 
%test:%    = [value of test:] 
%test::test=replace% = :test=replace 
%test::~0,4%   = :~0,4 
%test:more%   = more 

With extensions disabled 
------------------------- 
%test:%  = [value of test:] 
%test:more% = [value of test:more] 

的扩张究竟是如何工作的变量的完整说明,请参见https://stackoverflow.com/a/7970912/1012053

+1

+1尼斯详细的解释按照你的惯常:) –