Windows command prompt: Using a variable set in the same line of a one-liner

后端 未结 4 1326
别那么骄傲
别那么骄傲 2021-02-13 23:29

Okay, I learned that one can use & or && to combine multiple commands into a single line, but it seems that variables that are set

4条回答
  •  余生分开走
    2021-02-14 00:05

    You can do it in the same line, but I would recommend to use a batch file like preHook.bat.

    As one liner

    set "mu=hello, world!" && call echo %^mu%
    

    At first you can see that the quotes are different than yours.


    Here's why:

    set test1="quotes"
    set "test2=no quotes" with comment
    

    In the first test, the quotes will be part of the test1 variable, as well as all characters after the last quote.

    In the second test, it uses the extended syntax of the SET command.
    So the content will be no quotes, as only the content to the last quote is used; the rest will be dropped.

    To echo the variable content, I use call echo %^mu%, as percent expansion will expand it when the line is parsed, before any of the commands are executed.

    But the call command will be executed later, and it restarts the parser, which, when used at the command line, uses different expansion rules than the batch parser: an empty variable (in this case, %^mu%, in the first time) stays unchanged in the line; but, in the next parser phase, the ^ caret will be removed.

    In your case, call echo %mu% would also work, but only when mu is always empty. The caret variant also works when mu has content before the line is executed.

    More about the parser at SO: How does the Windows Command Interpreter (CMD.EXE) parse scripts? And about variable expansion at SO: Variable expansion

提交回复
热议问题