Batch equivalent of Bash backticks

2019-01-02 18:03发布

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.

5条回答
像晚风撩人
2楼-- · 2019-01-02 18:23

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

查看更多
何处买醉
3楼-- · 2019-01-02 18:29

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.

查看更多
浅入江南
4楼-- · 2019-01-02 18:33

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
查看更多
牵手、夕阳
5楼-- · 2019-01-02 18:41

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%
查看更多
笑指拈花
6楼-- · 2019-01-02 18:43

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

查看更多
登录 后发表回答