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

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Reino
Posts: 23
Joined: 14 May 2015 06:13
Contact:

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

#1 Post by Reino » 22 Nov 2021 05:25

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 "?

aGerman
Expert
Posts: 4325
Joined: 22 Jan 2010 18:01
Location: Germany

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

#2 Post by aGerman » 22 Nov 2021 11:07

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

Reino
Posts: 23
Joined: 14 May 2015 06:13
Contact:

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

#3 Post by Reino » 22 Nov 2021 17:52

So it's actually a bug. I see.
Thanks for your quick reply.

jeb
Expert
Posts: 993
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

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

#4 Post by jeb » 23 Nov 2021 01:21

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

Reino
Posts: 23
Joined: 14 May 2015 06:13
Contact:

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

#5 Post by Reino » 27 Nov 2021 08:20

That's some weird stuff, but it works. Thanks, jeb!

Post Reply