Home computickets (bat) Accessing a variable from if

(bat) Accessing a variable from if

Author

Date

Category

I needed to fence a bat file and ran into a problem.
Code with a loop, inside which there is a condition. And a variable that is assigned if the condition is triggered. I expect to see ewq in echo qwe later, but I see initially only the assigned value outside the loop (2 times).

@echo off
  SetLocal EnableExtensions
  Set a = q
  Set C = 1 3 2
  FOR %% x IN (% C%) DO (
  IF %% x == 1 (
  Set a = qwe
  echo% a%
  )
  IF %% x == 2 (
  Set a = ewq
echo% a%
  )
  )
  pause

if I remove the initial assignment Set a = q, then I get “echo command output mode disabled” and that’s it. How do I assign and refer to a variable?


Answer 1, authority 100%

I expect to see ewq in echo qwe later, but initially I see only the assigned value outside the loop (2 times).

You need to enable EnableDelayedExpansion and use ! a! .

When EnableDelayedExpansion is disabled (not set), the value of the variables is fixed at the start of the block, and any change is ignored. Even if it was altered by the previous line.

When EnableDelayedExpansion is enabled, the value of the variable is similarly fixed, and the fixed value is obtained when accessed if a percent sign is used, or changed if an exclamation mark is used.

Parse code:

@ echo off
cls
SetLocal
set test = test
echo Without EnableDelayedExpansion
for %% x in (1) do (
  set test = altered
  echo% test%
  echo! test!
)
echo finally:% test%
SetLocal EnableDelayedExpansion
set test = test
echo.
echo With EnableDelayedExpansion
for %% x in (3) do (
  set test = altered
  echo% test%
  echo! test!
)
echo finally:% test%

if I remove the initial assignment Set a = q then I get “echo command output mode disabled”

It is necessary to provide for such an event.

Here is the correct code:

@ echo off
SetLocal EnableExtensions EnableDelayedExpansion
Set a = q
Set C = 1 3 2
FOR %% x IN (% C%) DO (
  IF "%% x" == "1" (
    Set a = qwe
    echo! a!
  )
  IF "%% x" == "2" (
    Set a = ewq
    echo! a!
  )
)
pause

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions