Batch equivalent of Bash backticks
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.
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).
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%
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
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.
You could always run Bash inside Windows. I do it all the time with MSYS (much more efficient than Cygwin).
精彩评论