1

I am having difficulty understanding how batch file localization works. Here is an example to demonstrate my confusion

@echo off
set x=5
set y=1
setlocal enabledelayedexpansion
if %y% GEQ 1 (
   set x=6
   echo %x%
   echo !x!
)
echo %x%
endlocal

echo %x%

This prints, 5 6 6 5 And if I remove the IF statement, it prints, 6 6 6 5 What a mess! Why is it like this? In Linux bash files I know exactly what will happen but not here. Please explain to me what is going on in each of the print statements, and what the best way is to code for variables that are modified in IF blocks.

I had to use setlocal to solve another problem

@echo off
set x=5
set y=1
if %y% GEQ 1 (
   set x=6
   echo %x%
)
echo %x%

This print 5 6 despite my expectation of 6 6. Then I learned about setlocal to fix this that is now another headache.

Compo
  • 36,585
  • 5
  • 27
  • 39
danny
  • 1,101
  • 1
  • 12
  • 34
  • 1
    Well, `echo %x%` in the `if` clause returns the value of `x` present before the whole `if` block is executed, which has nothing to do with environment localisation. When you remove the `if` block, the remaining lines become parsed one after another since there is no more block... – aschipfl May 31 '20 at 15:54
  • The term `localization` typically implies the work done to make a program resources work in another human culture. This would include language translation (English, German, Japanese, etc.). – lit Jun 01 '20 at 01:20
  • @lit, whilst your statement is often true, environment localisation in Windows Command Prompt has absolutely nothing to do with language and region settings; it localises current working directories and changes of environment variables to a certain batch script (section)… – aschipfl Jun 02 '20 at 12:10
  • @aschipfl, I wonder if there would be less confusion with a different term. What about "scope" to refer to the scope of variables? Environment variable scoping? – lit Jun 02 '20 at 14:35
  • 1
    @lit, this type of localisation is more related to local variables or functions available in a lot of programming languages. The term *»localisation of environment changes«* comes from Microsoft – type [`setlocal /?`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/setlocal) and [`endlocal /?`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/endlocal) into Command Prompt. I agree that *»scope«* might have been a better choice… – aschipfl Jun 02 '20 at 15:18
  • @aschipfl - Well, if it comes from Microsoft... well... there you are. :-) – lit Jun 02 '20 at 15:27

0 Answers0