Delayed expansion in for loop

Viewed 115

Delayed expansion acts weird in my for loop. At the first iteration study is defined, at the second iteration it seems the delayed expansion doesn't work (delayed expansion is used just to strip the colon out because that will be the name of a directory). It is like that cypress command breaks something. Is that somehow related to how that cypress CLI works or there is something wrong with my script?

@echo off
setlocal EnableExtensions EnableDelayedExpansion    

:parse
IF "%~1"=="" GOTO endparse
IF "%~1"=="-s" SET studies=%~2
SHIFT
GOTO parse
:endparse


for %%a in ("%studies:,=" "%") do (
set tmp=%%~na
set study=!tmp::=!
echo study %%~a delayedExString: !study!
npx cypress run -study=%%~a --config videosFolder=cypress/videos/!study! --headless --spec "cypress/integration/*"
)

Example:

myscript.bat -s "firstStudy:Chap1,secondStudy:Chap3"

Console output:

study firstStudy:Chap1 delayedExString firstStudyChap1
[...cypress log...]


study secondStudy:Chap3 delayedExString !study!
[...cypress log...]

As you can see, in the second iteration study is not expanded.

1 Answers

One root cause for different behavior in subsequent iterations is the exit of the batch parser to the command line parser.

This happens inside loops by starting another batch file without CALL.
I suppose in your case it's npx.

To solve this, just add CALL

call npx cypress run ...

Starting another batch file without call results in transfer the execution context to the other batch file without returning.
Normally this results into an end after the second batch file ends and returning to the command line context.
But in a loop, the loop will still be completed.

A simple check for this behavior is to add a dummy function call.

for %%a in ("%studies:,=" "%") do (
   call :dummy
   ....
)

:dummy
exit /b

The first loop works, but then an error occurs:

Invalid attempt to call batch label outside of batch script.

Related