Batch equivalent of Bash backticks

BashBatch FileBackticks

Bash Problem Overview


When working with Bash, I can put the output of one command into another command like so:

my_command `echo Test`

would be the same thing as

my_command Test

(Obviously, this is just a non-practical example.)

I'm just wondering if you can do the same thing in Batch.

Bash Solutions


Solution 1 - Bash

You can get a similar functionality using cmd.exe scripts with the for /f command:

for /f "usebackq tokens=*" %%a in (`echo Test`) do my_command %%a

Yeah, it's kinda non-obvious (to say the least), but it's what's there.

See for /? for the gory details.

Sidenote: I thought that to use "echo" inside the backticks in a "for /f" command would need to be done using "cmd.exe /c echo Test" since echo is an internal command to cmd.exe, but it works in the more natural way. Windows batch scripts always surprise me somehow (but not usually in a good way).

Solution 2 - Bash

You can do it by redirecting the output to a file first. For example:

echo zz > bla.txt
set /p VV=<bla.txt
echo %VV%

Solution 3 - Bash

Read the documentation for the "for" command: for /?

Sadly I'm not logged in to Windows to check it myself, but I think something like this can approximate what you want:

for /F %i in ('echo Test') do my_command %i

Solution 4 - Bash

Maybe I'm screwing up the syntax of the standard for /f method, but when I put a very complex command involving && and | within the backticks in the limit of the for /f, it causes problems. A slight modification from the usual is possible to handle an arbitrary complexity command:

SET VV=some_command -many -arguments && another_command -requiring -the-other -command | handling_of_output | more_handling
for /f "usebackq tokens=*" %%a in (`%VV%`) do mycommand %%a

By putting your full and complex command in a variable first, then putting a reference to the variable in the limit rather than putting the complex command directly into the limit of the for loop, you can avoid syntax interpretation issues. Currently if I copy the exact command I have set to the VV variable in the example above into where it's used, %VV%, it causes syntax errors.

Solution 5 - Bash

You could always run Bash inside Windows. I do it all the time with MSYS (much more efficient than Cygwin).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMiffTheFoxView Question on Stackoverflow
Solution 1 - BashMichael BurrView Answer on Stackoverflow
Solution 2 - BashzvrbaView Answer on Stackoverflow
Solution 3 - BashWeebleView Answer on Stackoverflow
Solution 4 - BashmtalexanView Answer on Stackoverflow
Solution 5 - BashdavrView Answer on Stackoverflow