How to refer to a variable in Batch Scripting?

2019-09-16 05:11发布

Imagine a script called batch.bat, invoked like this:

batch.bat Two

The script contains:

set One=1
set Two=2
set Three=3

set Choice=%1

echo %Choice%

But I want to echo 2, not Two.

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.

Edit: I also tried:

set percent=%%
echo %percent%%Choice%%percent%

But it won't treat the resulting expression as a variable reference.

2条回答
贼婆χ
2楼-- · 2019-09-16 05:56
@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.

查看更多
beautiful°
3楼-- · 2019-09-16 06:01

OK, I have figured it out:

The key is to use the "set delayed expansion" trick. There's also a trick using the "call set" instead of the above but I reckon if I use that, the next guy after me won't know what I was trying to do and might get in trouble.

The script can be fixed by adding !! around the reference that we want to force into the variable name, like so:

@echo off
setlocal EnableDelayedExpansion

set One=1
set Two=2
set Three=3

set Choice=!%1!

echo %Choice%
查看更多
登录 后发表回答