4

Should I always put setlocal enableDelayedExpansion at the start a batch script, even when I don't need it?

Does it have any impact on performance, or will it cause any problem?

lzhh
  • 852
  • 7
  • 16
  • 2
    It is unnecessary to use delayed expansion for every script, and needs to be accounted for if dealing with paths or strings containing `!` exclamation marks. – T3RR0R Mar 24 '21 at 08:25
  • 2
    No, you should not. Delayed expansion should be enabled only when really needed as it cause double parsing of each command line and and cause troubles on file/folder names or other strings contain a exclamation mark. For that reason `setlocal enableDelayedExpansion` should be used only when really needed and knowing about the consequences regarding to `!` in file/folder names and other strings. I recommend to read the issue chapters of [this answer](https://stackoverflow.com/a/60686543/3074564) for some general hints on how to write batch files. – Mofi Mar 24 '21 at 09:35
  • 3
    Double parsing, but not double executing. I'm going to be the voice of dissent and say that processing filenames that contain a `!` is really the only reason to not have delayed expansion everywhere, and other than that, I can't think of a single other reason not to. Like spaces, exclamation points shouldn't be in file names anyway. – SomethingDark Mar 24 '21 at 09:44

1 Answers1

5

I enable delayed expansion nearly always at the beginning of any batch file.

Because it has two main advantages:

  • Expansion of !varname! is evaluated when the expression is executed, not when it is parsed, like percent expansion, this avoid many problems
  • The expanded content is always safe and will not be (re)parsed further, special characters doesn't harm
  • The setlocal prevents the environment of polution with local variables

The only drawback is the handling of exclamation marks itself.
But even that can be solved with some glue code

jeb
  • 78,592
  • 17
  • 171
  • 225
  • 1
    Recently I found that `enableddelayedexpansion` also makes arraies possible in batch, like `set /a integer_%index%=100` or `echo int_%index% = !integer_%index%!`. That's exciting. – lzhh Apr 18 '21 at 03:20