5

In linux, this takes one command, and passes its output (stdout) to another:

echo `ls`

What is the Windows/cmd/batch equivalent?

17

cmd.exe offers a rudimentary command substitution facility using backticks, but only via the for loop with the /f usebackq option. It's pretty brain-dead compared to what a Unix shell would do, however, as its standard behavior is to pick up only the first word of each line of output from the child and only so you can iterate over them, not so you can paste all of them at once onto the command line. (You can adjust the behavior somewhat with the delims option.) Here's an example:

for /f usebackq %F in (`dir /w s*c`) do echo %F

If you want genuine Unix-style command substitution, you'll need a genuine Unix shell, e.g., either Cygwin bash or my own (commercial) Hamilton C shell.

3

Example of echo output of dir (use single quotes, not backtick !):

echo off & for /f "delims=" %A in ('dir') do echo %A

In interactive mode, you need type echo on and press Enter to exit. If you are sure that loop only run once (i.e. output of ('xxx') is single line), then you can direct append echo on in the command.

echo off & for /f "delims=" %A in ('set /a 0x3DE1') do net helpmsg %A & echo on

For unknown reason, ('set /a 0x3DE1') can't do like 'set /a c=0x3DE1', even though set /a c=0x3DE1 is works as single command.

Example of echo hello world from 'echo hello world' (single quotes):

echo off & for /f "delims=" %A in ('echo hello world') do echo %A

Example of echo hello world from "" (literal string):

echo off & for /f "delims=" %A in ("hello world") do echo %A

Above syntax %A is for interactive mode, you need double % in batch file, e.g. %%A

Take care if you do echo %A inside the loop, imagine if one of the line from output of command called on, then there are 2 problems:

[1] echo $A means echo on which will echo nothing and invisible. I can only think of comparing the on to handle such specific case.

[2] echo $A means echo on which will toggle back the command prompt output; You might need add extra echo off inside the loop., e.g.:

echo off & for /f "delims=" %A in ('dir /b') do echo %A & echo off

Note that above examples is far from equivalent to `` since it run argument line by line. You may create this batch to try to simulate echo `ls` (it loop and append all the lines into single variable separate by space and then pass as argument later):

@echo off
Setlocal EnableDelayedExpansion
set fls=
for /f "delims=" %%A in ('dir /b') do set fls=!fls! %%A
echo %fls%

-- edit : added missing spaces

1
  • You can put the for ... echo %A into round brackets and then append & echo on. This way echo on runs after all of the echos inside the loop.
    – chapluck
    Apr 2 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.