Set and print content of environment variable in cmd.exe subshell?How can I display the contents of an environment variable from the command prompt in Windows 7?Setting and getting Windows environment variables from the command prompt?cmd.exe SET command does not save values for new cmd.exe sessionsSet enviroment variable setxUsing an environment variable set to a path value: the system cannot find the path specified for %OPENCV_DIR%How can I set temporary environment for explorer (renewed)how to set up an environment variable that it stores a path along with another env variable but doesnt expandsNested environment variable does not expandedAre there rules to Windows 7 Environment variable names?How can I set a dynamically evaluated environment variable for Windows' Command Processor (cmd.exe)?How to set Base64 encryption key as Environment (system) Variable on Windows 10

Aliens englobed the Solar System: will we notice?

Offered promotion but I'm leaving. Should I tell?

What is the chance of making a successful appeal to dismissal decision from a PhD program after failing the qualifying exam in the 2nd attempt?

Why does the negative sign arise in this thermodynamic relation?

Why the color red for the Republican Party

Accountant/ lawyer will not return my call

Who deserves to be first and second author? PhD student who collected data, research associate who wrote the paper or supervisor?

Virginia employer terminated employee and wants signing bonus returned

Why does Captain Marvel assume the people on this planet know this?

Set and print content of environment variable in cmd.exe subshell?

How could our ancestors have domesticated a solitary predator?

Should QA ask requirements to developers?

Why is Beresheet doing a only a one-way trip?

Make a transparent 448*448 image

What wound would be of little consequence to a biped but terrible for a quadruped?

Why is this plane circling around the Lucknow airport every day?

Can't find the Shader/UVs tab

Rejected in 4th interview round citing insufficient years of experience

Do items de-spawn in Diablo?

Can someone explain what is being said here in color publishing in the American Mathematical Monthly?

Things to avoid when using voltage regulators?

Time travel short story where dinosaur doesn't taste like chicken

Does "variables should live in the smallest scope as possible" include the case "variables should not exist if possible"?

Why don't MCU characters ever seem to have language issues?



Set and print content of environment variable in cmd.exe subshell?


How can I display the contents of an environment variable from the command prompt in Windows 7?Setting and getting Windows environment variables from the command prompt?cmd.exe SET command does not save values for new cmd.exe sessionsSet enviroment variable setxUsing an environment variable set to a path value: the system cannot find the path specified for %OPENCV_DIR%How can I set temporary environment for explorer (renewed)how to set up an environment variable that it stores a path along with another env variable but doesnt expandsNested environment variable does not expandedAre there rules to Windows 7 Environment variable names?How can I set a dynamically evaluated environment variable for Windows' Command Processor (cmd.exe)?How to set Base64 encryption key as Environment (system) Variable on Windows 10













5















Consider this example, where I start a new "sub" instance of cmd.exe, and then try to set a new environment variable in it, and then check if it has the proper value set (this is in cmd.exe of Windows 10):



>cmd /c "SET OPERATION=NEW & SET O"
OneDrive=C:UsersuserOneDrive
OPERATION=NEW
OS=Windows_NT


So, as noted in https://superuser.com/a/776506/688965 - by doing SET O I would "display all variables that begin with the letter 'O'", and indeed, it shows that an environment variable OPERATION exists, and its value is NEW. So far, so good.



However, if I try to print the environment value instead, it does not expand:



>cmd /c "SET OPERATION=NEW & echo %OPERATION%"
%OPERATION%


... however, if I try to expand any other environment variable, it works ?!:



>cmd /c "SET OPERATION=NEW & echo %OS%"
Windows_NT


Why does this happen? How can I set an environment variable, and then print it with echo in a single line, in a cmd.exe subshell?










share|improve this question

















  • 3





    "Why does this happen?" The %OPERATION% is executed before it has been set. See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details.

    – DavidPostill
    10 hours ago











  • Thanks @DavidPostill - feel free to post this as an answer, I'll accept it!

    – sdbbs
    10 hours ago















5















Consider this example, where I start a new "sub" instance of cmd.exe, and then try to set a new environment variable in it, and then check if it has the proper value set (this is in cmd.exe of Windows 10):



>cmd /c "SET OPERATION=NEW & SET O"
OneDrive=C:UsersuserOneDrive
OPERATION=NEW
OS=Windows_NT


So, as noted in https://superuser.com/a/776506/688965 - by doing SET O I would "display all variables that begin with the letter 'O'", and indeed, it shows that an environment variable OPERATION exists, and its value is NEW. So far, so good.



However, if I try to print the environment value instead, it does not expand:



>cmd /c "SET OPERATION=NEW & echo %OPERATION%"
%OPERATION%


... however, if I try to expand any other environment variable, it works ?!:



>cmd /c "SET OPERATION=NEW & echo %OS%"
Windows_NT


Why does this happen? How can I set an environment variable, and then print it with echo in a single line, in a cmd.exe subshell?










share|improve this question

















  • 3





    "Why does this happen?" The %OPERATION% is executed before it has been set. See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details.

    – DavidPostill
    10 hours ago











  • Thanks @DavidPostill - feel free to post this as an answer, I'll accept it!

    – sdbbs
    10 hours ago













5












5








5








Consider this example, where I start a new "sub" instance of cmd.exe, and then try to set a new environment variable in it, and then check if it has the proper value set (this is in cmd.exe of Windows 10):



>cmd /c "SET OPERATION=NEW & SET O"
OneDrive=C:UsersuserOneDrive
OPERATION=NEW
OS=Windows_NT


So, as noted in https://superuser.com/a/776506/688965 - by doing SET O I would "display all variables that begin with the letter 'O'", and indeed, it shows that an environment variable OPERATION exists, and its value is NEW. So far, so good.



However, if I try to print the environment value instead, it does not expand:



>cmd /c "SET OPERATION=NEW & echo %OPERATION%"
%OPERATION%


... however, if I try to expand any other environment variable, it works ?!:



>cmd /c "SET OPERATION=NEW & echo %OS%"
Windows_NT


Why does this happen? How can I set an environment variable, and then print it with echo in a single line, in a cmd.exe subshell?










share|improve this question














Consider this example, where I start a new "sub" instance of cmd.exe, and then try to set a new environment variable in it, and then check if it has the proper value set (this is in cmd.exe of Windows 10):



>cmd /c "SET OPERATION=NEW & SET O"
OneDrive=C:UsersuserOneDrive
OPERATION=NEW
OS=Windows_NT


So, as noted in https://superuser.com/a/776506/688965 - by doing SET O I would "display all variables that begin with the letter 'O'", and indeed, it shows that an environment variable OPERATION exists, and its value is NEW. So far, so good.



However, if I try to print the environment value instead, it does not expand:



>cmd /c "SET OPERATION=NEW & echo %OPERATION%"
%OPERATION%


... however, if I try to expand any other environment variable, it works ?!:



>cmd /c "SET OPERATION=NEW & echo %OS%"
Windows_NT


Why does this happen? How can I set an environment variable, and then print it with echo in a single line, in a cmd.exe subshell?







windows command-line cmd.exe environment-variables






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 11 hours ago









sdbbssdbbs

1627




1627







  • 3





    "Why does this happen?" The %OPERATION% is executed before it has been set. See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details.

    – DavidPostill
    10 hours ago











  • Thanks @DavidPostill - feel free to post this as an answer, I'll accept it!

    – sdbbs
    10 hours ago












  • 3





    "Why does this happen?" The %OPERATION% is executed before it has been set. See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details.

    – DavidPostill
    10 hours ago











  • Thanks @DavidPostill - feel free to post this as an answer, I'll accept it!

    – sdbbs
    10 hours ago







3




3





"Why does this happen?" The %OPERATION% is executed before it has been set. See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details.

– DavidPostill
10 hours ago





"Why does this happen?" The %OPERATION% is executed before it has been set. See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details.

– DavidPostill
10 hours ago













Thanks @DavidPostill - feel free to post this as an answer, I'll accept it!

– sdbbs
10 hours ago





Thanks @DavidPostill - feel free to post this as an answer, I'll accept it!

– sdbbs
10 hours ago










2 Answers
2






active

oldest

votes


















3














Why does this happen?



The %OPERATION% is expanded (Phase 1) before the variable has been set (Phase 7).



See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details:




Processing a line of code in a batch file involves multiple phases.



Here is a brief overview of the various phases:



Phase 0) Read Line:



Phase 1) Percent Expansion:



Phase 1.5) Remove : Remove all Carriage Return (0x0D) characters



Phase 2) Process special characters, tokenize, and build a cached
command block: This is a complex process that is affected by things
such as quotes, special characters, token delimiters, and caret
escapes.



Phase 3) Echo the parsed command(s) Only if the command block did not
begin with @, and ECHO was ON at the start of the preceding step.



Phase 4) FOR %X variable expansion: Only if a FOR command is active
and the commands after DO are being processed.



Phase 5) Delayed Expansion: Only if delayed expansion is enabled



Phase 5.3) Pipe processing: Only if commands are on either side of a
pipe



Phase 5.5) Execute Redirection:



Phase 6) CALL processing/Caret doubling: Only if the command token is
CALL



Phase 7) Execute: The command is executed







share|improve this answer






























    5














    How can I set an environment variable, and then print it with echo in a single line, in a cmd.exe subshell?



    To enable neccessary delayed expansion in a cmd subshell you'll have to use the /V:ON switch of cmd.exe and use an ! exclamation mark instead of the % percent sign.



    > cmd /V:ON /C "SET OPERATION=NEW&echo [!OPERATION!]"
    [NEW]


    Just a reminder

    The trailing space in your original set will be part of the variable content:



    > cmd /V:ON /C "SET OPERATION=NEW &echo [!OPERATION!]"
    [NEW ]





    share|improve this answer
























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "3"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f1413376%2fset-and-print-content-of-environment-variable-in-cmd-exe-subshell%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      Why does this happen?



      The %OPERATION% is expanded (Phase 1) before the variable has been set (Phase 7).



      See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details:




      Processing a line of code in a batch file involves multiple phases.



      Here is a brief overview of the various phases:



      Phase 0) Read Line:



      Phase 1) Percent Expansion:



      Phase 1.5) Remove : Remove all Carriage Return (0x0D) characters



      Phase 2) Process special characters, tokenize, and build a cached
      command block: This is a complex process that is affected by things
      such as quotes, special characters, token delimiters, and caret
      escapes.



      Phase 3) Echo the parsed command(s) Only if the command block did not
      begin with @, and ECHO was ON at the start of the preceding step.



      Phase 4) FOR %X variable expansion: Only if a FOR command is active
      and the commands after DO are being processed.



      Phase 5) Delayed Expansion: Only if delayed expansion is enabled



      Phase 5.3) Pipe processing: Only if commands are on either side of a
      pipe



      Phase 5.5) Execute Redirection:



      Phase 6) CALL processing/Caret doubling: Only if the command token is
      CALL



      Phase 7) Execute: The command is executed







      share|improve this answer



























        3














        Why does this happen?



        The %OPERATION% is expanded (Phase 1) before the variable has been set (Phase 7).



        See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details:




        Processing a line of code in a batch file involves multiple phases.



        Here is a brief overview of the various phases:



        Phase 0) Read Line:



        Phase 1) Percent Expansion:



        Phase 1.5) Remove : Remove all Carriage Return (0x0D) characters



        Phase 2) Process special characters, tokenize, and build a cached
        command block: This is a complex process that is affected by things
        such as quotes, special characters, token delimiters, and caret
        escapes.



        Phase 3) Echo the parsed command(s) Only if the command block did not
        begin with @, and ECHO was ON at the start of the preceding step.



        Phase 4) FOR %X variable expansion: Only if a FOR command is active
        and the commands after DO are being processed.



        Phase 5) Delayed Expansion: Only if delayed expansion is enabled



        Phase 5.3) Pipe processing: Only if commands are on either side of a
        pipe



        Phase 5.5) Execute Redirection:



        Phase 6) CALL processing/Caret doubling: Only if the command token is
        CALL



        Phase 7) Execute: The command is executed







        share|improve this answer

























          3












          3








          3







          Why does this happen?



          The %OPERATION% is expanded (Phase 1) before the variable has been set (Phase 7).



          See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details:




          Processing a line of code in a batch file involves multiple phases.



          Here is a brief overview of the various phases:



          Phase 0) Read Line:



          Phase 1) Percent Expansion:



          Phase 1.5) Remove : Remove all Carriage Return (0x0D) characters



          Phase 2) Process special characters, tokenize, and build a cached
          command block: This is a complex process that is affected by things
          such as quotes, special characters, token delimiters, and caret
          escapes.



          Phase 3) Echo the parsed command(s) Only if the command block did not
          begin with @, and ECHO was ON at the start of the preceding step.



          Phase 4) FOR %X variable expansion: Only if a FOR command is active
          and the commands after DO are being processed.



          Phase 5) Delayed Expansion: Only if delayed expansion is enabled



          Phase 5.3) Pipe processing: Only if commands are on either side of a
          pipe



          Phase 5.5) Execute Redirection:



          Phase 6) CALL processing/Caret doubling: Only if the command token is
          CALL



          Phase 7) Execute: The command is executed







          share|improve this answer













          Why does this happen?



          The %OPERATION% is expanded (Phase 1) before the variable has been set (Phase 7).



          See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for the gory details:




          Processing a line of code in a batch file involves multiple phases.



          Here is a brief overview of the various phases:



          Phase 0) Read Line:



          Phase 1) Percent Expansion:



          Phase 1.5) Remove : Remove all Carriage Return (0x0D) characters



          Phase 2) Process special characters, tokenize, and build a cached
          command block: This is a complex process that is affected by things
          such as quotes, special characters, token delimiters, and caret
          escapes.



          Phase 3) Echo the parsed command(s) Only if the command block did not
          begin with @, and ECHO was ON at the start of the preceding step.



          Phase 4) FOR %X variable expansion: Only if a FOR command is active
          and the commands after DO are being processed.



          Phase 5) Delayed Expansion: Only if delayed expansion is enabled



          Phase 5.3) Pipe processing: Only if commands are on either side of a
          pipe



          Phase 5.5) Execute Redirection:



          Phase 6) CALL processing/Caret doubling: Only if the command token is
          CALL



          Phase 7) Execute: The command is executed








          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 10 hours ago









          DavidPostillDavidPostill

          106k26228263




          106k26228263























              5














              How can I set an environment variable, and then print it with echo in a single line, in a cmd.exe subshell?



              To enable neccessary delayed expansion in a cmd subshell you'll have to use the /V:ON switch of cmd.exe and use an ! exclamation mark instead of the % percent sign.



              > cmd /V:ON /C "SET OPERATION=NEW&echo [!OPERATION!]"
              [NEW]


              Just a reminder

              The trailing space in your original set will be part of the variable content:



              > cmd /V:ON /C "SET OPERATION=NEW &echo [!OPERATION!]"
              [NEW ]





              share|improve this answer





























                5














                How can I set an environment variable, and then print it with echo in a single line, in a cmd.exe subshell?



                To enable neccessary delayed expansion in a cmd subshell you'll have to use the /V:ON switch of cmd.exe and use an ! exclamation mark instead of the % percent sign.



                > cmd /V:ON /C "SET OPERATION=NEW&echo [!OPERATION!]"
                [NEW]


                Just a reminder

                The trailing space in your original set will be part of the variable content:



                > cmd /V:ON /C "SET OPERATION=NEW &echo [!OPERATION!]"
                [NEW ]





                share|improve this answer



























                  5












                  5








                  5







                  How can I set an environment variable, and then print it with echo in a single line, in a cmd.exe subshell?



                  To enable neccessary delayed expansion in a cmd subshell you'll have to use the /V:ON switch of cmd.exe and use an ! exclamation mark instead of the % percent sign.



                  > cmd /V:ON /C "SET OPERATION=NEW&echo [!OPERATION!]"
                  [NEW]


                  Just a reminder

                  The trailing space in your original set will be part of the variable content:



                  > cmd /V:ON /C "SET OPERATION=NEW &echo [!OPERATION!]"
                  [NEW ]





                  share|improve this answer















                  How can I set an environment variable, and then print it with echo in a single line, in a cmd.exe subshell?



                  To enable neccessary delayed expansion in a cmd subshell you'll have to use the /V:ON switch of cmd.exe and use an ! exclamation mark instead of the % percent sign.



                  > cmd /V:ON /C "SET OPERATION=NEW&echo [!OPERATION!]"
                  [NEW]


                  Just a reminder

                  The trailing space in your original set will be part of the variable content:



                  > cmd /V:ON /C "SET OPERATION=NEW &echo [!OPERATION!]"
                  [NEW ]






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 1 hour ago

























                  answered 10 hours ago









                  LotPingsLotPings

                  5,0801823




                  5,0801823



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Super User!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f1413376%2fset-and-print-content-of-environment-variable-in-cmd-exe-subshell%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Best approach to update all entries in a list that is paginated?Best way to add items to a paginated listChoose Your Country: Best Usability approachUpdate list when a user is viewing the list without annoying themWhen would the best day to update your webpage be?What should happen when I add a Row to a paginated, sorted listShould I adopt infinite scrolling or classical pagination?How to show user that page objects automatically updateWhat is the best location to locate the comments section in a list pageBest way to combine filtering and selecting items in a listWhen one of two inputs must be updated to satisfy a consistency criteria, which should you update (if at all)?

                      Тонконіг бульбистий Зміст Опис | Поширення | Екологія | Господарське значення | Примітки | Див. також | Література | Джерела | Посилання | Навігаційне меню1114601320038-241116202404kew-435458Poa bulbosaЭлектронный каталог сосудистых растений Азиатской России [Електронний каталог судинних рослин Азіатської Росії]Малышев Л. Л. Дикие родичи культурных растений. Poa bulbosa L. - Мятлик луковичный. [Малишев Л. Л. Дикі родичи культурних рослин. Poa bulbosa L. - Тонконіг бульбистий.]Мятлик (POA) Сем. Злаки (Мятликовые) [Тонконіг (POA) Род. Злаки (Тонконогові)]Poa bulbosa Linnaeus, Sp. Pl. 1: 70. 1753. 鳞茎早熟禾 lin jing zao shu he (Description from Flora of China) [Poa bulbosa Linnaeus, Sp. Pl. 1: 70. 1753. 鳞茎早熟禾 lin jing zao shu he (Опис від Флора Китаю)]Poa bulbosa L. – lipnice cibulkatá / lipnica cibulkatáPoa bulbosa в базі даних Poa bulbosa на сайті Poa bulbosa в базі даних «Global Biodiversity Information Facility» (GBIF)Poa bulbosa в базі даних «Euro + Med PlantBase» — інформаційному ресурсі для Євро-середземноморського розмаїття рослинPoa bulbosa L. на сайті «Плантариум»

                      Вунгтау (аеропорт) Загальні відомості | Див. також | Посилання | Навігаційне меню10°22′00″ пн. ш. 107°05′00″ сх. д. / 10.36667° пн. ш. 107.08333° сх. д. / 10.36667; 107.0833310°22′00″ пн. ш. 107°05′00″ сх. д. / 10.36667° пн. ш. 107.08333° сх. д. / 10.36667; 107.083337731608Vinh AirportVinh airport facelift improves serviceвиправивши або дописавши їївиправивши або дописавши їїр