0

why doesn't this work?

SET FIRST=""
SET COUNT=0
FOR %%F IN (dir *.png) DO (
  IF %COUNT% NEQ 0 GOTO _skip
  SET FIRST=%%F
:_skip
  ECHO "%%F",
  SET /A COUNT=COUNT+1
)

It sets FIRST to the last *.png because the IF condition fails, because COUNT - although is incremented by set /A, the IF %COUNT% doesn't ever work. Very frustrating.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
user306517
  • 523
  • 8
  • 21
  • 1
    1. you are not really working with **DOS**, are you (`set /A` was not supported back then!)? 2. you'll need [delayed variable expansion](http://stackoverflow.com/a/10558905/5047996) as you modify and read `COUNT` within the `for` loop; 3. do *not* use `goto` within code blocks like `for` since they break the block context; – aschipfl Oct 08 '15 at 00:07
  • In general, it would be very helpful if you described what "not working" means and what you expected your code to do... – aschipfl Oct 08 '15 at 01:09

1 Answers1

1

Don't need to count, just do goto skip after echo line.

@echo off
for /f "delims=" %%f in ('dir /b *.png') do (
  rem :: you can use "echo %%f" instead of "set first=%%f"
  set first=%%f
  goto _skip
)
:_skip
echo %first%

you mixing two things to scan folder.

Here is the second way:

@echo off
for %%f in (*.png) do (
  set first=%%f
  goto _skip
)
:_skip
echo %first%
exit /b 0

If you need absolutely to count, here is the way to skip with count. As stated in comment, you need to enable delayedExpansion

@echo off

set count=1
for %%f in (*.png) do (
  set first=%%f
  setlocal enabledelayedexpansion
  if "!count!"=="1" goto _skip
  endlocal
  set /a count+=1
)
:_skip
echo !first!
Paul
  • 2,620
  • 2
  • 17
  • 27
  • why did you place `setlocal` in the `for` body? why not stating it once before `for`? – aschipfl Oct 08 '15 at 00:53
  • 1
    @aschipfl because filename with "!" I put expansion where is needed. I don't remember which post explain this – Paul Oct 08 '15 at 00:58
  • Okay, good point! however, you need `endlocal` then *before* `set /a` to disable the delayed expansion for the next `for` loop iteration... – aschipfl Oct 08 '15 at 01:04