2014-03-03 126 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尼斯詳細的解釋按照你的慣常:) –