Home > OS >  windows - batch - for (can somebody explain How does this code work?)
windows - batch - for (can somebody explain How does this code work?)

Time:12-01

windows - batch - for (can somebody explain How does this code work?)

@echo off

for /f %%i in ('dir f* /s /aD /b 2^> nul ^| find "" /v /c') do set VAR=%%i

echo %VAR% > output.txt

here is the output in this directory

CodePudding user response:

[1] Execute dir f* /s /aD /b - this lists all names-only (/b) in the directory and in subdirectories (/s) that are directories (/ad) and match the name-mask f*
[2] 2^> nul - suppress error messages (ie - no matching names found)
[3] ^| - send the output of the dir command to find
[4] find "" /v /c - find any line that does not (/v) contain nothing ("") and output the count of such lines (/c)
[5] The resultant count-string is assigned to %%i by the for command
[6] And then to the variable by the set

The caret (^) tells cmd that the symbol following is part of the command to be executed, not of the for.

See for /?, dir /?, find /? and set /? from the prompt for details, or thousands of examples on SO.

  • Related