Home Variables in batch not behaving as expected
Reply: 1

Variables in batch not behaving as expected

Eric Marcinowski
Eric Marcinowski Published in 2015-05-17 02:35:49Z

I've been wrestling trying to get the syntax right on this batch file and I can't for the LIFE of me figure out why some things aren't working.

1) The variable 'i' is not getting incremented. and 2) Concatenation on strc doesn't seem to want to...well, concatenate.

set i=0
set "strc=concat:"

for %%f in (*.mp4) do (
    set /a i+=1
    set "str=intermediate%i%.ts"

    set strc="%strc% %str%|"

    ffmpeg -i "%%f" -c copy -bsf:v h264_mp4toannexb -f mpegts "%str%"

set strc="%strc:-1%"
ffmpeg -i "%strc%" -c copy -bsf:a aac_adtstoasc Output.mp4
Stephan Reply to 2017-09-11 10:41:18Z

You are not the first, who fell into the famous "delayed expansion trap" (and you won't be the last)

You need delayed expansion if you want to use a variable, that you changed in the same block (a block is a series of commands within brackets (and ))

Delayed variables are referenced with !var! instead of %var%

Reason is the way, cmd parses the code. A complete line or block is parsed at once, replacing normal variables with their value at parse time. Delayed variables are evaluated at runtime.

Two simple batches to demonstrate:

setlocal enabledelayedexpansion
set "var=hello"
if 1==1 (
  set "var=world"
  echo %var% !var!


for /L %%i in (1,1,5) do (
  echo %random% !random!

Note: also a line is treated as a block:

set "var=old"
set "var=new" & echo %var% 

with delayed expansion:

setlocal enabledelayedexpansion
set "var=old"
set "var=new" & echo !var! 

Delayed expansion is per default turned off at the command prompt. If you really need it, you can do:

cmd /v:on /c "set "var=hello" & echo !var!"
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.398523 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO