Dirk
Dirk

Reputation: 1324

Evaluate environment variable read from file in batch

I read in the file repos.txt by the script:

@echo off

for /F %%s in (%~dp0repos.txt) do (
    echo %%s
)

The file repos.txt contains the lines:

%UserProfile%\Documents\Repository\A
%UserProfile%\Documents\Repository\B

The echo command gives me the directories without evaluating the environment variable %UserProfile%. This is a problem when I would like to use it with git.

How can I evaluate the environment variable?

I tried setlocal like done here and the surrounding with exclamation marks. Unfortunately, nothing gives the correct output.

Upvotes: 1

Views: 383

Answers (1)

Mofi
Mofi

Reputation: 49216

Command call can be used to expand environment variables on assigning to an environment variable as this code demonstrates:

@echo off
setlocal EnableDelayedExpansion
for /F "usebackq eol=| delims=" %%s in ("%~dp0repos.txt") do (
    set "RepositoryPath=%%s"
    echo Not expanded: !RepositoryPath!
    call set "RepositoryPath=%%s"
    echo And expanded: !RepositoryPath!
)
endlocal

Upvotes: 2

Related Questions