Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

windows - Exiting batch with `EXIT /B X` where X>=1 acts as if command completed successfully when using && or || operators between batch calls

I'm trying to chain a series of .bat files using the EXIT /B X command to return success or failure and && and || for conditional running of the next .bat (e.g. a.bat && b.bat).

Regardless of whether I call EXIT /B 0 or anything else to end a.bat, a.bat && b.bat will call b.bat afterward. My understanding is that EXIT /B 0 should set ERRORLEVEL=0, which is success, so the && should continue. The counterpoint to this is that calling EXIT /B 1 should set ERRORLEVEL=1 which is failure, so the && should stop. What am I missing here?

Trivialized example:

For non-batch commands, acting as expected:

C:> echo test|findstr test>NUL && echo yes
yes

C:> echo test|findstr test>NUL || echo yes

C:> echo test|findstr nope>NUL && echo yes

C:> echo test|findstr nope>NUL || echo yes
yes

Using EXIT /B always sees a.bat as successful:

C:> echo @EXIT /B 0 > a.bat

C:> a.bat && echo yes
yes

C:> a.bat || echo yes

C:> echo @EXIT /B 1 > a.bat

C:> a.bat && echo yes
yes

C:> a.bat || echo yes

How can I exit from a.bat so that a.bat && b.bat and a.bat || b.bat behave as expected?

All commands are run in cmd.exe on Windows XP SP3.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you ask me, exit codes in batch files are broken for this exact reason, but there is a hacky workaround you can use. As the last line of your batch file, use:

@%COMSPEC% /C exit 1 >nul

Since this is an actual process that is started you get a real process exit code and && and || will work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...