Search code examples
batch-filefor-loopskip-lists

How to fix my batch for loop to store the last line?


I have a file called cmd.pid and in this file i store the pid of all cmd.exe running on the computer.

I need to store the last line of the file (because its the last cmd open)

This is to send commands on the cmd window thanks to the pid i save.

for /f "skip=2 delims=" %%i in ('type "mypath\cmd.pid"') do set "line=%%i" & goto done
:done
echo line^=!line!

The value of the 3rd line of my file isn't in !line! The program stop when i launch it.

This is what my cmd.pid file store :

16992      

12300      

The first line is 16992, 2nd line is blank and the last line is 12300. You can't see it but there is spaces (6 exactly) after each pid


Solution

  • The easy way would have been to remove the instruction

    goto done
    

    and remove the skip=? entirely (although it would do no harm.)

    That way, each value read from the file is assigned to line in turn, so the very last value remains when the for loop terminates at the end-of-file.