Search code examples
filebatch-fileappendecho

what is the difference between echo %%~fF and echo %%~fF >> file.txt within recursive calls


i want to list subdirectories with a given level of nesting. console display works just fine, but while appending the same echo to a file it behaves different.

@echo off
setlocal

set currentLevel=0
set maxLevel=%1
if not defined maxLevel set maxLevel=1
 
:procFolder
pushd %1 2>nul
if %currentLevel% lss %maxLevel% (
  for /d %%F in (*) do (
    echo %%~fF
    echo %%~fF >> list.txt
    set /a currentLevel+=1
    call :procFolder "%%F"
    set /a currentLevel-=1
  )
)
popd

calling the batch-file with parameter 3 writes to the shell with the expected nesting of three subfolders

D:\erroronline1\code\learntoshell\sub1
D:\erroronline1\code\learntoshell\sub1\sub2
D:\erroronline1\code\learntoshell\sub1\sub2\sub3

but in the actual file there is just the first level of recursion written down

D:\erroronline1\code\learntoshell\sub1

this happens to all possible subfolders, just first level nesting is appended. i could not control the level of nesting with other methods of listing subdirectories (for /r %%F in (.), dir /s) so this doesn't appear as an option. pausing the recursion (to wait for the file being written, whatever) or passing the folder to a variable didn't help either.

what am i missing? what is possibly the difference between echo and echo >> file within a recursive call?


Solution

  • pushd changes the current directory. The redirected echo output is appended to a file in the current directory.

    Change the logfile from current directory to a full path and you will get all the logging in one file instead of several files in the nested directories.