I do not agree with some of the description in the link.
See exit /?
accurate help description.
exit
exits the interpreter.
exit 1
exits the interpreter with exitcode 1.
exit /b
has similar behavior as goto :eof
which exits
the script or called label. Errorlevel is not reset so allows
errorlevel from the previous command to be accessable after
exit of the script or the called label.
exit /b 1
exits the script or the called label with errorlevel 1.
If you oddly use exit /b
at a CMD prompt, it is going to exit the interpreter.
Main code:
@ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
SET args=%*
SET "self=%~f0"
IF "%selfWrapped%"=="" (
@REM this is necessary so that we can use "exit" to terminate the batch file,
@REM and all subroutines, but not the original cmd.exe
SET "selfWrapped=true"
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO !ComSpec! /s /c ""!self!" !args!"
"!ComSpec!" /s /c ""!self!" !args!"
GOTO :EOF
)
ECHO(%*
EXIT /B 0
Both use of GOTO :EOF
and EXIT /B 0
will exit the script.
ENDLOCAL
is implied at exit of the script.
Explicit use of ENDLOCAL
is for when you want to end the
current local scope and continue the script. As always, being
explicit all the time is a choice.
Setting %*
to args
keeps the double quoting paired.
Quoting i.e. set "args=%*"
can cause issue sometimes
though not using quotes allow code injection i.e.
arguments "arg1" ^& del *.*
. If the del *.*
is not going
to execute at the set
line, then it will probably happen
at the ComSpec
line. For this example, I chose not quote.
So, it is a choice.
You are using disabled expansion at start of the script. That
saves the !
arguments which is good. Before you execute
ComSpec
though, enable delayed expansion and use !args!
which is now protected from the interpreter now not seeing |
or any other special character which may throw an error.
Your script fails as the |
argument is exposed.
C:\Windows\system32\cmd.exe /s /c ""test.cmd" " | ""
The above is echoed evaluation of the ComSpec
line with
setting @ECHO ON
. Notice the pairing of quotes
i.e. ""
, " "
and ""
. Notice the extra spacing inserted
around the |
character as the interpreter does not consider
it as part of a quoted string.
Compared to updated code changes of echoed evaluation...:
"!ComSpec!" /s /c ""!self!" !args!"
The string between the quotes remain intact. No extra spacing
inserted into the string. The echoed evalution looks good and
executes good.
Disclaimer:
Expressing the workings of CMD is like walking a tight rope.
Just when you think you know, fall off the rope you go.