I'm creating a batch file and I'm having trouble with the following command:
echo Hello & echo.World > Text.txt
Whenever I do this command the output only shows the last line, like so:
World
But if I just do the above command in CMD without writing to a file, it appears perfectly in the command prompt. I have complete access over my file but I still can't seem to be able to write the whole text.
In batch, the >
operator has higher precedence than the &
operator, so your example is only redirecting the last command echo.World
to the file. The first command is still outputting to the console.
To redirect multiple commands, you can surround them with parentheses.
(echo Hello & echo.World) > Text.txt
In batch & is a command-separator. You can produce the same result by using two separate echo
lines.
echo Hello & echo.World > Text.txt
executes as two independent commands,
echo Hello echo.World > Text.txt
which would report Hello
to the console and write World
to the file (you didn't mention that Hello
appeared on the console...)
Note that > creates a new file whereas >> appends to any existing file (or creates a new file) so
echo Hello > Text.txt
echo.World > Text.txt
would first write Hello
to a new file, then overwrite it with World
.
To append the second line, you'd need
echo Hello > Text.txt
echo.World >> Text.txt
or, on one line,
echo Hello > Text.txt&echo.World >> Text.txt
A parenthesised statement-sequence (aka a "block") is regarded as one complex statement, so
(echo Hello &echo.World)> Text.txt
would create a new file containing both lines, whereas
(echo Hello &echo.World)>> Text.txt
would append the two lines to any existing file.
Note also that the trailing spaces before the > will also be written to the file.
Be very careful about > and >>. if the command you execute is
echo Hello 1> Text.txt
then helloSpace will be written to the file.
If a message terminating with Spacea single digit is written to a file, then well, probably nothing will appear. When we have this situation, the digit immediately before the > determins which 'logical deviceoutput will be used. The useful ones here are 1 (standard output) and 2(standard error) so you can redirect errormessages using
2>errorreports.txt` for instance.
If you have this situation, you can overcome this characteristic by using
> Text.txt echo Hello 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With