[8.x] Bugfix passing errorlevel when command is run in background #37423
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
On windows machines, when console commands are run in background, using
$schedule->command('inspire')->runInBackground()
an
errorlevel
variable is supposed to be passed to the schedule:finish command, enabling the after hooks for success/failureHowever, default behaviour in the cmd.exe shell is that variables are read and expanded line-by-line.
As the background commands are started in a fresh cmd.exe instance, and contain a single-line command, the errorlevel variable is not set to the exit code of the command, and will always be the default 0.
This prevents using the onFailure... methods on the scheduled command as it will always take the succesful route.
in a fresh terminal:
cmd /c exit 2 & echo "errorlevel=%errorlevel%"
will display "errorlevel=0"
while executing this line twice in a terminal:
cmd /c exit 2 & echo "errorlevel=%errorlevel%"
cmd /c exit 4 & echo "errorlevel=%errorlevel%"
will display
"errorlevel=0"
"errorlevel=2" --> at this time the errorlevel set in the first line is used.
This behaviour can be changed by enabling delayed expansion (https://ss64.com/nt/delayedexpansion.html), however setting this with SETLOCAL would also require a newline itself.
So probably the best thing to do is using the
command1 && command2 || command3
syntax (https://ss64.com/nt/syntax-redirection.html), in which case command 2 (finishing succesful with errorlevel 0) is only executed when command1 is succesfuly run, otherwise command 3 (finishing with errorlevel 1) is executed.Note that command3 will also be executed when command 2 may fail.