如何在批处理脚本中引用变量?
问题描述:
想象一个名为batch.bat的脚本,其调用方式如下:
Imagine a script called batch.bat, invoked like this:
batch.bat Two
该脚本包含:
set One=1
set Two=2
set Three=3
set Choice=%1
echo %Choice%
但是我要回显 2
而不是两个
。
我可以采用哪种优雅的方式来做到这一点?我考虑过 if%Choice%= One,等等。
,但是我的实际脚本比提供的示例复杂一些。
What elegant way can I employ to do that? I thought about if %Choice%=One, etc.
but my actual script is a bit more complex than the example provided.
编辑:我也尝试过:
set percent=%%
echo %percent%%Choice%%percent%
但是它不会将结果表达式视为变量引用。
But it won't treat the resulting expression as a variable reference.
答
@echo off
setlocal EnableDelayedExpansion
set one=1
set c=%1
echo delayed expansion and variable: !%c%!
echo delayed expansion and paramr: !%1!
call echo using call and variable: %%%c%%%
call echo using call and param: %%%1%%
我个人更喜欢延迟扩展方法,但有时有理由寻找替代方法。
I personally prefer the delayed expansion method, but sometimes there are reasons to look for an alternative.