0

As the title says I have a problem saving (and therefore printing) string variables in my bat script. The problem occurs when I try working with strings that start and/or end with '!'. Example:

@echo off
pause
setlocal ENABLEDELAYEDEXPANSION
for /r %%f in (*.png *.jpg *.gif *.webp *.jpeg) do (

set curr_name=%%~nxf
set curr_path=%%~dpf

@echo !curr_path!!curr_name!

@echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
)
pause

For file named !a.png and a!.png it prints out a.png and for !a!.png it just prints out .png. I've been trying to find answer for this but no luck. Sorry if I'm missing something obvious here and thanks for any tips!

1 Answer 1

1

With delayed expansion enabled, this is expected behaviour. your shown use case does not require variables to be assigned - you could just use the relevant For variable modifiers.

If for some reason you need to use delayed expansion (for exmple performing substring modification), delayed expansion should be toggled on / off during the loop after the variable has been assigned:

Example:

@echo off

 for /r %%f in (*.png *.jpg *.gif *.webp *.jpeg) do (
  set "curr_name=%%~nxf"
  set "curr_path=%%~dpf"
  Setlocal enabledelayedexpansion
  echo(!curr_path!!curr_name!
  endlocal
  @echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 )

pause
Sign up to request clarification or add additional context in comments.

2 Comments

The example I posted was the gutted part of the full script and I do need delayed expansion outside and inside this for loop. Do you suggest wrapping every part that needs it with setlocal enabledelayedexpansion/endlocal?
That would depend upon the rest of your 'gutted' code, which we cannot see. Enabling it for the entire script would generally be fine, as long as you will not need to use strings containing exclamation points, otherwise, enable it and use it only where required.

Your Answer

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