Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Logically your failing code equates to</p> <pre><code>setlocal enableDelayedExpansion ( set VAR1=success set VAR2=VAR1 set VAR3=!%VAR2%! echo VAR3=!VAR3! ) </code></pre> <p>As has already been pointed out in previous answers and comments, you can't assign a value to VAR2 and then access the value using %VAR2% within the same code block because %VAR2% is expanded during the parsing phase of the code block, at which point the value is not what you want (probably undefined).</p> <p>But you need a second level of expansion in addition to !VAR2! to get the result you want. I know of three solutions.</p> <p><strong>1)</strong> This solution works, but it is not recommended because it is slow.</p> <pre><code>setlocal enableDelayedExpansion ( set VAR1=success set VAR2=VAR1 call set VAR3=%%!VAR2!%% echo VAR3=!VAR3! ) </code></pre> <p>Prior to the execution of the CALL, each %% is reduced to %, and !VAR2! becomes VAR1. Thus the called statement becomes <code>set VAR3=%VAR1%</code>, and the called statement is reparsed through the %var% expansion phase, so you get your desired result.</p> <p>BUT - CALL is relatively very expensive. When used in a loop it can cause severe performance degradation. jeb provides a good demonstration and explanation at <a href="http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=1947&amp;p=8386#p8386" rel="nofollow" title="CALL me, or better avoid call">CALL me, or better avoid call</a></p> <p><strong>1a)</strong> There is a variation of the CALL solution where you call a :LABELed subroutine. Because the subroutine is parsed after the call, you can simply use <code>set VAR3=!%VAR2%!</code>. But again, this uses CALL so it is relatively slow and not recommended.</p> <p><strong>2)</strong> This general solution works, and is <em>MUCH</em> faster in comparison. It uses a FOR variable for the second level of expansion. This is the recommended solution.</p> <pre><code>setlocal enableDelayedExpansion ( set VAR1=success set VAR2=VAR1 for /f %%A in ("!VAR2!") do set VAR3=!%%A! echo VAR3=!VAR3! ) </code></pre> <p><strong>3)</strong> If the value of VAR1 is known to be an integer, then there is a special case solution using <code>SET /A</code></p> <pre><code>setlocal enableDelayedExpansion ( set VAR1=999 set VAR2=VAR1 set /a VAR3=!VAR2! echo VAR3=!VAR3! ) </code></pre> <p>The SET /A command has its own built in expansion of variables that takes place after delayed expansion, and no punctuation is needed.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload