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.

2
  • 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 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; Commented Oct 8, 2015 at 0:07
  • In general, it would be very helpful if you described what "not working" means and what you expected your code to do... Commented Oct 8, 2015 at 1:09

1 Answer 1

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!
Sign up to request clarification or add additional context in comments.

3 Comments

why did you place setlocal in the for body? why not stating it once before for?
@aschipfl because filename with "!" I put expansion where is needed. I don't remember which post explain this
Okay, good point! however, you need endlocal then before set /a to disable the delayed expansion for the next for loop iteration...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.