Home > Enterprise >  The batch does not work randomly when starting the loop
The batch does not work randomly when starting the loop

Time:10-13

Why doesn't it work in my code random? I wrote setlocal EnableDelayedExpansion. But in the loop, random still does not work. Keep giving the same number

setlocal EnableDelayedExpansion

set /A TrackNumber=!RANDOM! %% 3   1

FOR /F "tokens=*" %%G IN ('dir /b *.mp4') DO (

echo !TrackNumber!

ffmpeg -i "%%G" -i !TrackNumber!.mp3 -filter_complex "[0:a][1:a]amerge=inputs=2[a]" -map 0:v -map "[a]" -c:v copy -ac 2 -shortest .%%~nG.mp4

)

CodePudding user response:

I don't think it will recursively expand even when delayed. And even if it could, you are doing set /A TrackNumber=!RANDOM! ... after enabling delayed expansion so TrackNumber just starts with a number, not the string !RANDOM!.

You can just update the variable every time inside the loop:

@echo off 
setlocal EnableDelayedExpansion

for /L %%a in (0,1,9) do (
    set /A TrackNumber=!RANDOM! %% 42   1

    echo Test#%%a: !TrackNumber!
)

And if for some reason you need to keep the expression outside the loop:

@echo off
set TrackNumberExpr=%%random%% %%%% 42   1
setlocal EnableDelayedExpansion

for /L %%a in (0,1,3) do (
    call set /A TrackNumber=!TrackNumberExpr!
    echo Test#%%a: !TrackNumber!
)

for /L %%a in (0,1,3) do (
    call set /A TrackNumber=!TrackNumberExpr!
    echo Test#%%a: !TrackNumber!
)
  • Related