-1

If you have a variable inside this for /f command, it doesn't get printed out to file.

setlocal EnableDelayedExpansion
for /F %%i in ('dir /B') do (
    set duration=asdf
    echo %duration% > file.txt
)

Contents of file.txt: Echo is ON.

If you move set duration=asdf out of for /f wrap and put it below setlocal line it works correct and prints asdf into file.txt

Why? How do I do this with the set variable inside the for command?

Squashman
  • 13,649
  • 5
  • 27
  • 36
user3108268
  • 1,043
  • 3
  • 18
  • 37
  • 2
    You enabled [delayed expansion](http://ss64.com/nt/delayedexpansion.html) but you are not using it; replace `%duration%` by `!duration!` to actually use it... – aschipfl Mar 29 '17 at 18:40
  • 1
    Despite duration not being set by the loop, there is no need to set anything, you would just echo %%i. – Compo Mar 29 '17 at 18:54
  • 1
    You were shown how to use Delayed Expansion in your previous question. What didn't you understand about it in your previous question? – Squashman Mar 29 '17 at 19:05

1 Answers1

1

This is due to delayed expansion, which stops variables from being set and used, in the same command.

You are getting Echo is ON. in file.txt, because to the command interpreter it's reading the echo command as:

echo > file.txt

Which as documented by echo /?

Type ECHO without parameters to display the current echo setting.


The simplest fix is to replace the % with !

Updated script:

setlocal EnableDelayedExpansion
for /F %%i in ('dir /B') do (
    set duration=asdf
    echo !duration! > file.txt
)
Sam Denty
  • 3,693
  • 3
  • 30
  • 43