Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMD or BATCH BNF grammar or parser reference

Tags:

batch-file

cmd

I'm looking over some batch files written by a coworker, and I ran into some weird syntax where he calls redirection operator at the beginning of his command.

This:

> output.txt ECHO something like this

rather than:

ECHO something like this > output.txt

It threw me off for a second. It works, so I assume its valid. I went to look for an official reference to confirm, but could not find one.

I did find this reference on the usage of the operator itself.

I found this bash version of what I'm looking for linked to here: POSIX sh EBNF grammar

What is the correct syntax for the use of the > and >> operators in batch?

Edit: To clarify, I'm not looking for examples as documentation. I would like to see documentation explaining how cmd.exe commands and .bat files are parsed specifically in regards to redirection operators.

like image 900
Pete Avatar asked Sep 12 '26 05:09

Pete


1 Answers

The official documentation for command redirection operators demonstrates their use at the end of the line. But putting the redirection at the beginning of the line is no less correct (piped output notwithstanding).

The benefit of putting the redirect at the beginning of an echo line is that you avoid echoing a trailing space into the file.

echo Hello world! > out.txt

15 bytes, includes a trailing space.

> out.txt echo Hello world!

14 bytes, does not include a trailing space

You can also use parentheses to avoid the trailing space.

(echo Hello world!) > out.txt

14 bytes

Parentheses can also be used to group the output of several commands without having to close and reopen the file handle for each line.

rem // option 1
> out.txt (
    echo Hello world!
    echo Another line
)

rem // option 2
(
    echo Hello world!
    echo Another line
) > out.txt

Both of those parenthetical code blocks perform the exact same action. And both are more efficient than this:

rem // option 3
>out.txt echo Hello world!
>>out.txt echo Another line

The parenthetical examples in options 1 and 2 above open, write, and close "out.txt" only one time; whereas the option 3 example opens, writes, closes, opens for appending, writes, and closes. When dumping a lot of data to a text file, such optimizations can make a difference.

like image 90
rojo Avatar answered Sep 16 '26 04:09

rojo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!