2

I am writing a batch library that must not be local, so that external batch files may call upon the functions from a single defined location.

This requires that the calling batch file must pass in a "unique" identifier for the variables named within. (I.E. pass in Application1 for %1).

I then wish to dynamically name variables, such as:

set %1_Timer=Hello

This works well, except I need to be able to evaluate said dynamic variables, but cannot find a solution that allows me to evaluate these parameter based dynamic variables.

I've tried solutions such as:

echo %1_Timer%
echo %1_Timer
echo %%1_Timer%%
echo %%1_Timer%
Call echo %%1%_Timer%

I cannot use a variable that is not dynamically named as other scripts utilizing this library might alter that non-dynamic variable, altering the output for other scripts.

Ryan
  • 23
  • 2
  • 1
    See [arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990). The mechanism to access your dynamic variables is the same of an _array_. – Aacini Apr 09 '15 at 04:44

2 Answers2

2

You want to use delayed expansion.

@echo off
setlocal enabledelayedexpansion

echo !%1_Timer!

You could also use call and %% signs (call echo %%%1_Timer%%, but generally delayed expansion will be more useful. Also, it is mandatory if you ever set or modify a variable inside of a code block like a for or an if.

SomethingDark
  • 13,229
  • 5
  • 50
  • 55
  • I specified it could not be local. The same library will be called multiple times, and if local is set, then the same variables won't be accessible, defeating the function of the library. - I do see that you add a method I could use CALL for without utilizing local though. – Ryan Apr 09 '15 at 14:53
  • @Ryan - Oh, I assumed that meant that it couldn't be on your local machine. (I know that doesn't make any sense, but we see all kinds of weird questions here so I just rolled with it.) – SomethingDark Apr 09 '15 at 15:19
0
@ECHO OFF
SETLOCAL
SET myapp_timer=original_value
CALL :appsee myapp
CALL :appset myapp
CALL :appsee myapp
GOTO :EOF

:: set variable(s) - can be external batch to set caller's environment
:appset
SET %1_timer=hello
GOTO :EOF

:: see variable(s) - can be external batch to set caller's environment
:appsee
CALL ECHO %%1_timer=%%%1_timer%%
GOTO :EOF

Here's how.

Magoo
  • 77,302
  • 8
  • 62
  • 84