一个命令的输出设置为变量(含管道) [英] Set output of a command as a variable (with pipes)
问题描述
你能使用的管道命令的输出重定向到一个变量?
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 method (with two variations)...
例如:
echo Hello|set text=
没有工作,也没有:
Didn't work, neither did:
echo Hello | set text=
我知道你可以用的
命令做到这一点很容易,但我认为它看起来漂亮与管道。
I know you can do it fairly easily with the FOR
command, but I think it would look "nicer" with a pipe.
如果你想知道,我没有,我问这个以外我很好奇,我无法找到答案的具体原因。
And if you're wondering, I don't have a specific reason I'm asking this other than I'm curious and I can't find the answer.
推荐答案
您的方法不能,原因有二。
Your way can't work for two reasons.
您需要使用设置/ p =文本
用于设置变量的用户输入的。结果
另一个问题是在管道上。结果,
一个管道启动两个异步cmd.exe的实例,并在完成作业后两种情况下是关闭的。
You need to use set /p text=
for setting the variable with user input.
The other problem is the pipe.
A pipe starts two asynchronous cmd.exe instances and after finishing the job both instances are closed.
这就是为什么的原因,似乎这两个变量没有设置,但一个小的例子表明,它们设置但结果是后来丢失了。
That's the cause why it seems that the variables are not set, but a small example shows that they are set but the result is lost later.
set myVar=origin
echo Hello | (set /p myVar= & set myVar)
set myVar
输出
Hello
origin
替代:您可以用FOR循环获取值变量或者也临时文件
Alternatives: You can use the FOR loop to get values into variables or also temp files.
for /f "delims=" %%A in ('echo hello') do set "var=%%A"
echo %var%
或
>output.tmp echo Hello
>>output.tmp echo world
<output.tmp (
set /p line1=
set /p line2=
)
echo %line1%
echo %line2%
这篇关于一个命令的输出设置为变量(含管道)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!