批处理文件变量名有哪些限制,为什么?
我注意到我无法用 name 回显变量:)。
h:\uprof>set :)=123
h:\uprof>set :)
:)=123
h:\uprof>echo %:)%
%:)%
Run Code Online (Sandbox Code Playgroud)
从批处理文件显然:)是输出而不是%:)%. 问题显然不在于set命令,因为变量及其值出现在set.
奇怪的是,当分开 -:或)- 和反转 - ):- 当用作变量名称时,所有输出它们的给定值。
唯一不能出现在用户定义的批处理环境变量名称中的字符是=. SET 语句将在第一次出现时终止变量名,=之后的所有内容都将成为该值的一部分。
分配一个包含 a 的变量名很简单:,但除非在特定情况下,否则通常无法扩展该值。
启用扩展时(默认行为)
冒号是搜索/替换和子字符串扩展语法的一部分,它会干扰名称中包含冒号的变量的扩展。
有一个例外——如果:出现在名称的最后一个字符,那么变量可以很好地扩展,但是你不能对值进行搜索和替换或子字符串扩展操作。
当扩展被禁用时
搜索/替换和子字符串扩展不可用,因此没有什么可以阻止包含冒号的变量的扩展正常工作。
@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%
Run Code Online (Sandbox Code Playgroud)
- 输出 -
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]
Run Code Online (Sandbox Code Playgroud)
请参阅/sf/answers/557963871/以获取有关变量扩展工作原理的完整说明。
:是用于变量扩展的字符串操作特殊字符。例子:
%var:~0,1%
Run Code Online (Sandbox Code Playgroud)
因此,如果:变量名后面有任何内容,它将尝试执行字符串操作并失败。这允许:冒号字符本身或当没有任何东西跟随它时。
关于扩展变量名称的规则:变量名称后面不能包含:任何字符,否则变量扩展将失败。
set :)=123
set a)=123
set :a=123
set :=123
set )=123
echo %:)%
echo %a)%
echo %:a%
echo %:%
echo %)%
Run Code Online (Sandbox Code Playgroud)
输出:
%:)%
123
%:a%
123
123
Run Code Online (Sandbox Code Playgroud)