views:

315

answers:

5

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.

A: 

Probably not. The cmd.exe shell doesn't have as many features as bash. However, you may check out powershell as it's pretty exciting in comparison to bash (when it comes to Windows scripting).

xyld
+3  A: 

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%
zvrba
not a bad workaround
xyld
It requires you to find a place where you have write access to store the temporary file; you have to clean up after yourself; this very example only enables you to read the very first line of input. For all practical purposes the `for /f` variant is a much better one.
Joey
+6  A: 

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

Michael Burr
Well, everything in that line is executed by `cmd` anyway; why would you need to spawn a subshell for commands that are perfectly legal there already?
Joey
@Johannes: I seem to remember situations where trying to execute internal commands had to be done by specifying `cmd.exe` or `command.com` (this might be some dark memory from MS-DOS days), but I don't recall the details - I might even be entirely mistaken. I was mildly surprised (but not greatly surprised) when `echo` worked in this case without spawning `cmd.exe`. Maybe I'm getting confused by times I had to configure other programs to execute internal commands. I should probably just get rid of the note.
Michael Burr
You usually have to do this when executing shell-builtins from external programs that don't automatically spawn a shell. I.e. C's `system()` was fine, iirc, since it starts a shell in any case but .NET's `Process.Start` needs to explicitly invoke the shell. Something like that, iirc. In any case, I consider this to be the better answer than the accepted one :-)
Joey
A: 

You could always run bash inside windows. I do it all the time with MSys (much more efficient than Cygwin).

davr
+1  A: 

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
Weeble