Reputation: 481
Assume I have a compound command (multiple simple CMD commands joined by operators &
,&&
and/or ||
). I surround it by parentheses and afterwards put another conditional execution operator (&&
or ||
) followed by e.g. the command DIR
.
The success of failure of what simple command(s) within my compound command will matter when the interpreter decides whether my DIR
command is to be executed or not?
I have done some experimenting and it seems that only the success or failure of the very last simple command from my compound command is decisive for the execution of DIR
.
But then I came across this page, which says "Use parenthesis to test the success of several commands". This implies that the interpreter somehow aggregates error levels returned by the simple commands within the compound one do decide whether (in my example) DIR
is to be executed or not.
So I am confused...
Upvotes: 4
Views: 887
Reputation: 130919
Your original understanding is correct, the &&
and ||
operators respond to the most recently executed command (or operation)
The following claim on the original page you referenced was wrong.
Use parenthesis to test the success of several commands:
(Dir C:\Test1 & Dir C:\Test2) || Echo One or more of the commands failed.
The above will only echo the error message if the 2nd DIR failed.
The test could be corrected by using &&
instead of &
, but that is a simple result of logic, not some additional feature. Also, the code short circuits - if the first DIR command fails, then the second one will not execute.
(Dir C:\Test1 && Dir C:\Test2) || echo One of the DIR commands failed.
And the parentheses are not needed. The following gives the exact same result
Dir C:\Test1 && Dir C:\Test2 || echo One of the DIR commands failed.
In my very first sentence I said &&
and ||
can respond to an operation because they respond to operations like redirection.
The following will ECHO a custom error message if the redirection fails or if the DIR fails. Note that redirection occurs before the execution of the command. If the redirection fails, then the command is never executed:
dir c:\test >x:\output.log || echo Redirection or dir failed
The content of the referenced page has been corrected since this Q&A was posted :-)
Upvotes: 4