0

I'm working on a bat script that's supposed to move around some build artifacts. I need it to loop through a few different values (represented below as ABC, DEF, and GHI). I also would like to create temporary environment variables along the way. However, the environment variables introduced inside the loop don't ever get expanded.

@echo on

setlocal EnableDelayedExpansion

:: Remove the OutputMSI directory
set output=OutputMSI

for %%x in (ABC DEF GHI) do (
    :: Create a new Output tree
    set products_dir=%output%\%%x\products
    mkdir %products_dir%

    :: Copy published files
    robocopy publish\%%x\ %products_dir% *.application *.deploy /s

    :: Copy Version.txt
    copy Version.txt %products_dir%
)

endlocal

This is what gets echoed (with comments inline):

C:\...>setlocal EnableDelayedExpansion

C:\...>set output=OutputMSI

C:\...>for %x in (ABC DEF GHI) do (
set products_dir=OutputMSI\%x\products
===>             ^^^^^^^^^    ^^^^^^^^ %output% gets expanded here
 mkdir
 ===>  ^^^^^^^^^ %products_dir% doesn't get expanded here
 robocopy publish\%x\  *.application *.deploy /s
 ===>                ^ or here
 copy Version.txt   
 ===>             ^^^^^^^ or here
)

C:\...>(
set products_dir=OutputMSI\ABC\products
 mkdir
 ===>  ^^^^^^^^^ %products_dir% still not expanded here
 robocopy publish\ABC\  *.application *.deploy /s
 ===>                ^ or here
 copy Version.txt   
 ===>             ^^^^^^^ or here
)
The syntax of the command is incorrect.

The variables get expanded on the set line, but then not after. What am I missing about for loops or setlocal?

I've tried without EnableDelayedExpansion, and I've tried doubling up the % around the variable names, but neither made it work.

1 Answer 1

2

setlocal EnableDelayedExpansion - there is the word "enable" in it. It only prepares batch to use delayed expansion. To actually use a delayed variable, enclose it between ! instead of %:

set var=XYZ
for %%x in (ABC DEF GHI) do (
    set var=%%x
    echo %%x, !var!, %var%
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.