将命令的输出设置为变量

将命令的输出设置为变量

本文介绍了将命令的输出设置为变量(带管道)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能用管道将命令的输出重定向到一个变量吗?

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=

没有用,也没有用:

echo Hello | set text=

我知道你可以用 FOR 命令很容易地做到这一点,但我认为它会用管道看起来更好".

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.

您需要使用 set/p text= 来设置带有用户输入的变量.
另一个问题是管道.
管道启动两个异步 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%

宏的替代方案:

你可以使用批处理宏,这有点像bash等价物

You can use a batch macro, this is a bit like the bash equivalent

@echo off

REM *** Get version string
%$set% versionString="ver"
echo The version is %versionString[0]%

REM *** Get all drive letters
`%$set% driveLetters="wmic logicaldisk get name /value | findstr "Name""
call :ShowVariable driveLetters

宏的定义可以在
SO:使用 MS 批处理文件将程序的输出分配给变量

这篇关于将命令的输出设置为变量(带管道)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 01:18