Set output of a command as a variable (with pipes)

前端 未结 6 1116
花落未央
花落未央 2020-12-01 05:09

Can you redirect the output of a command to a variable with pipes?

I haven\'t tried much as I haven\'t been able to think of anything to try, but I have tried one me

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 05:41

    I find myself a tad amazed at the lack of what I consider the best answer to this question anywhere on the internet. I struggled for many years to find the answer. Many answers online come close, but none really answer it. The real answer is

    (cmd & echo.) >2 & (set /p =)<2

    The "secret sauce" being the "closely guarded coveted secret" that "echo." sends a CR/LF (ENTER/new line/0x0D0A). Otherwise, what I am doing here is redirecting the output of the first command to the standard error stream. I then redirect the standard error stream into the standard input stream for the "set /p =" command.

    Example:

    (echo foo & echo.) >2 & (set /p bar=)<2

提交回复
热议问题