Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file: How to get variable's value using variable's name already stored in a string

1) Quick example:

set a="Hello"
set d="a"

Now, how do I get the value of "a" using (the value of) variable d? For example, the variable name could have been entered by a user using a prompt, or the name of the variable could have been sent to a function.

None of these ideas work:

set e=%%d%%

set e=%%%d%%%

set e=set e=%%d%%
%e%

After an hour of brainstorming and Googling, I have come up with this, but it seems too complicated and clumsy - is there really no other/easier way?:

set a="Hello"
set b="Good day"
set c="Good night"

set /p d="Give me a variable name"

call :GetVarVal %%%d%%% "e"

REM This now gives the correct value:
echo %e%

goto :eof

:GetVarVal
  set "%~2=%~1"
goto :eof

2) Also, sort of similar, is there a better way to do this (ideally without a custom function):

set a="C:\Users\Blah\Documents\MP4Box\MP4Box.exe"

call :get_drive_and_path a

echo %b%

goto :eof

:get_drive_and_path
  set b=%~dp1
goto :eof

Thanks!

like image 363
user1596274 Avatar asked Oct 02 '13 20:10

user1596274


People also ask

Can a batch file return a value?

By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number.

How do I echo a variable in CMD?

To reference a variable in Windows, use %varname% (with prefix and suffix of '%' ). For example, you can use the echo command to print the value of a variable in the form " echo %varname% ".

What is %% R in batch command?

/r - iterate through the folder and all subfolders, i.e. recursively. %%I - placeholder for a path/filename. The above command simply lists all files in the current folder and all subfolders. Follow this answer to receive notifications.


3 Answers

example without delayed expansion (preserves exclamation marks):

@echo off &setlocal
set "a=Hello!"
set "d=a"
call echo %%%d%%%

output:

Hello!
like image 111
Endoro Avatar answered Nov 03 '22 23:11

Endoro


If I understood you correctly, the trick called "delayed expansion" should work:

SETLOCAL ENABLEDELAYEDEXPANSION
SET a=Hello
SET b=a
ECHO This is the value of a: !%b%!
SETLOCAL DISABLEDELAYEDEXPANSION

Check how it works here

like image 7
pmod Avatar answered Nov 03 '22 23:11

pmod


Part 2

set file="C:\Users\Blah\Documents\MP4Box\MP4Box.exe"
for %%a in (%file%) do echo %%~dpa
like image 3
foxidrive Avatar answered Nov 04 '22 00:11

foxidrive