0

The flag 'delayed expansion' in the batch file is enabled. It starts with:

    @echo off
    setlocal EnableDelayedExpansion

The batch file intends to make a tree of all the '.c' files in the current folder and all of its subfolders. Here it is:

    :: -------------------
    :: Generate file tree
    :: -------------------
    @echo off
    setlocal EnableDelayedExpansion
    for /f %%a in ('copy /Z "%~f0" nul') do set "CR=%%a"

    :: 1. Delete old file trees
    :: -------------------------

    for /r %%x in (*FileTree.txt) do (
        REM echo."File %%x deleted"
        del "%%x"
    )

    :: 2. Generate new file tree
    :: -------------------------

    break > localFileTree.txt

    set mypath=
    set localPath=
    call :treeProcess
    goto :eof

    :treeProcess
    setlocal
    for %%f in (*.c) do (
        set localPath=%mypath%%%f
        echo.!localPath! >> %~dp0\localFileTree.txt
    )
    for /D %%d in (*) do (
        set mypath=%mypath%%%d\
        echo.!mypath!
        cd %%d
        call :treeProcess
        cd ..
    )
    endlocal

    exit /b

A variable can be referenced in several ways:

  • Without anything: mypath=...
  • With leading double percent signs: %%f or %%d
  • With percent signs at either side: %mypath%
  • With exclamation marks at either side: !mypath!

I'm getting a bit confused. I know it has something to do with the 'delayed expansion' flag that is switched on. But how do these variable references actually differ from each other?

K.Mulier
  • 8,069
  • 15
  • 79
  • 141
  • 1
    Type `set /?` in a command prompt window and read the help very carefully! In the last pages, delayed expansion is described and an example is provided. See also [this external resource](http://ss64.com/nt/delayedexpansion.html). – aschipfl Aug 22 '16 at 08:06
  • You are asking multiple questions, but for all are already answers on SO, even with the same title [Difference between %variable% and !variable! in batch file](http://stackoverflow.com/q/14354502/463115) – jeb Aug 22 '16 at 08:07
  • Thank you guys :-) These links are very helpful. – K.Mulier Aug 22 '16 at 08:11
  • Another one: [What is variable expansion, and what does EnableDelayedExpansion mean?](http://stackoverflow.com/questions/25324354/windows-batch-files-what-is-variable-expansion-and-what-does-enabledelayedexpa/25328044#25328044) – Aacini Aug 22 '16 at 12:53

0 Answers0