lit
lit

Reputation: 16226

How to reference a variable value from the name in a variable?

I have Googled and searched Stackoverflow with no success. Perhaps I do not know the correct words to use in order to find what I am seeking.

A simplistic view of the effort would be to check for the existence and correctness of project configuration variables. If these are not defined, then it is not setup correctly. Likewise, if the directory does not exist, then the project is not setup correctly.

=== project_setup.bat

@ECHO OFF
SET SOURCE_DIR=C:\src\project1
SET OBJECT_DIR=D:\intermediate\objects
SET TEST_DIR=C:\testing\project1
set SHIP_DIR=C:\final\project1

=== check_project_directories.bat

@ECHO OFF
SETLOCAL
SET EXITCODE=0

SET DIR_LIST=^
SOURCE_DIR ^
OBJECT_DIR ^
TEST_DIR ^
SHIP_DIR

FOR %%v IN (%DIR_LIST%) DO (
    IF NOT DEFINED %%v (
        ECHO %%v is not defined.
        SET EXITCODE=1
    ) ELSE (
        REM === How to use the value of the variable rather than the variable name?
        IF NOT EXIST "%%v" (
            ECHO Directory for %%v does not exist.
            SET EXITCODE=1
        )
    )
)

EXIT /B %EXITCODE%

Upvotes: 1

Views: 38

Answers (1)

Jason Faulkner
Jason Faulkner

Reputation: 6558

I believe this is the tidbit you need (in your ELSE statement):

SET VariableName=%%v
CALL SET VariableValue=%%!VariableName!%%
IF NOT EXIST "!VariableValue!" (
...

Or more succinctly (but less readable):

CALL SET VariableValue=%%%%v%%
IF NOT EXIST "!VariableValue!" (
...

Either will require you to change your SETLOCAL command to:

SETLOCAL EnableDelayedExpansion

Essentially by adding the CALL in front of the SET statement you are telling the script to parse the respective line again but perform substitutions first.

This essentially makes the CALL SET VariableValue=%%!VariableName!%% evaluate to:

SET VariableValue=%SOURCE_DIR%
SET VariableValue=%OBJECT_DIR%
...

As it goes through the loop iterations which will set the VariableValue to the respective variable value you previously defined in your configuration.

Upvotes: 1

Related Questions