Page 1 of 1

How to pipe the outcome of an if-statement to another command?

Posted: 22 Nov 2021 05:25
by Reino
I thought I knew quite a lot about Batch and CMD, but the following is puzzling me.

Code: Select all

ECHO test> 1.txt

IF EXIST 1.txt (TYPE 1.txt) ELSE (ECHO test)
test

(IF EXIST 1.txt (TYPE 1.txt) ELSE (ECHO test))
test
So far so good, but I really don't understand why I'm getting...

Code: Select all

(IF EXIST 1.txt (TYPE 1.txt) ELSE (ECHO test)) | 3rd-party-command ...
( was unexpected at this time.
...the moment I pipe the outcome of the IF-statement to another command.
I've tried to escape the inner parentheses, but to no avail.

In the meantime an alternative that does work for me:

Code: Select all

(TYPE 1.txt 2>NUL || ECHO test) | 3rd-party-command ...
Bonus question regarding this alternative:

Code: Select all

ECHO test | 3rd-party-command ...
ECHO test| 3rd-party-command ...
(ECHO test) | 3rd-party-command ...
(ECHO test)| 3rd-party-command ...
Only with the 2nd ECHO does the 3rd-party-command receive "test". In all other cases it's "test " (with an extra space at the end).
With parentheses around the ECHO-command why does it still put out "test "?

Re: How to pipe the outcome of an if-statement to another command?

Posted: 22 Nov 2021 11:07
by aGerman
It doesn't work along with EXIST while it works with other IF statements. Seems to be one of many other cmd bugs.

That the cmd adds a space before the closing parenthesis is a known behavior. Run your last line with ECHO turned ON in order to see the command line which is actually executed.

Steffen

Re: How to pipe the outcome of an if-statement to another command?

Posted: 22 Nov 2021 17:52
by Reino
So it's actually a bug. I see.
Thanks for your quick reply.

Re: How to pipe the outcome of an if-statement to another command?

Posted: 23 Nov 2021 01:21
by jeb
Hi Reino,

when using a pipe, both sides are executed in a subshell.
For doing this, the commands are rewritten and executed with cmd.exe, but "IF" statements frequently fails to be rewritten correctly.
Debug syntax errors in subshell code
Why does delayed expansion fail when inside a piped block of code?

It can be solved by adding an escaped space and escape the closing parenthesis.

Code: Select all

(^ if exist 1.txt (echo found^) else (echo not found^) ) | more

Re: How to pipe the outcome of an if-statement to another command?

Posted: 27 Nov 2021 08:20
by Reino
That's some weird stuff, but it works. Thanks, jeb!