Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

batch-file

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)...

For example:

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.

like image 709
BDM Avatar asked Feb 19 '13 07:02

BDM


People also ask

How do you pipe the output of a command to a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do you pipe the output of a command to a file in Linux?

In Linux, for redirecting output to a file, utilize the ”>” and ”>>” redirection operators or the top command. Redirection allows you to save or redirect the output of a command in another file on your system. You can use it to save the outputs and use them later for different purposes.


1 Answers

Your way can't work for two reasons.

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 

Outputs

Hello origin 

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% 

or

>output.tmp echo Hello >>output.tmp echo world  <output.tmp (   set /p line1=   set /p line2= ) echo %line1% echo %line2% 

Alternative with a macro:

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 

The definition of the macro can be found at
SO:Assign output of a program to a variable using a MS batch file

like image 108
jeb Avatar answered Sep 24 '22 12:09

jeb