简体   繁体   中英

Using “setlocal enabledelayedexpansion” in cmd prompt

Does setlocal enabledelayedexpansion only work in a batch file? How can setlocal enabledelayedexpansion be used in a cmd prompt?

You can enable delayed expansion in a command prompt with the command cmd /V:ON

From cmd /? :

/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.

Learn by example: Copy&Paste from my CMD window:

==>echo !os! %pp%
!os! %pp%

==>cmd /E:ON /V:ON /K set "pp=yy" & set pp & echo !os! !pp!

==>echo !os! %pp%
Windows_NT yy

==>exit
Environment variable pp  not defined
!os! !pp!

==>cmd /E:ON /V:ON /K set "pp=yy" ^& set pp ^& echo !os! !pp!
pp=yy
Windows_NT yy

==>echo !os! %pp%
Windows_NT yy

==>exit

==>echo !os! %pp%
!os! %pp%

==>

Explanation:

  • echo !os! %pp% echo !os! %pp% returns !os! %pp% !os! %pp% showing delayed expansion disabled and pp variable not defined in current CLI;
  • cmd /E:ON /V:ON /K set "pp=yy" & set pp & echo !os! !pp! returns nothing, new instance of the Windows command interpreter has delayed expansion enabled (see echo !os! %pp% output);
  • exit returns result of set pp & echo !os! !pp! set pp & echo !os! !pp! in a parent CLI instance: Environment variable pp not defined and !os! !pp! !os! !pp! ;
  • cmd /E:ON /V:ON /K set "pp=yy" ^& set pp ^& echo !os! !pp! returns pp=yy and Windows_NT yy in the new CLI instance (note all & escaped by ^ );
  • echo !os! %pp% echo !os! %pp% returns Windows_NT yy in the new CLI instance (it shows delayed expansion enabled and pp variable defined in the child CLI);
  • exit to a parent CLI instance;
  • echo !os! %pp% echo !os! %pp% returns !os! %pp% !os! %pp% again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM