ExecStopPost= should do what you want.
Additional commands that are executed after the service is stopped. This includes cases where the commands configured in ExecStop= were used, where the service does not have any ExecStop= defined, or where the service exited unexpectedly. This argument takes multiple command lines, following the same scheme as described for ExecStart=. Use of these settings is optional. Specifier and environment variable substitution is supported. Note that – unlike ExecStop= – commands specified with this setting are invoked when a service failed to start up correctly and is shut down again.
It is recommended to use this setting for clean-up operations that shall be executed even when the service failed to start up correctly. Commands configured with this setting need to be able to operate even if the service failed starting up half-way and left incompletely initialized data around. As the service's processes have been terminated already when the commands specified with this setting are executed they should not attempt to communicate with them.
Note that all commands that are configured with this setting are invoked with the result code of the service, as well as the main process' exit code and status, set in the $SERVICE_RESULT, $EXIT_CODE and $EXIT_STATUS environment variables, see systemd.exec(5) for details.
In your script you can read
$EXIT_STATUS environment variables and take appropriate action.
You can use the following workaround with
systemd < 232.
#! /bin/bash --
## Non standard exit code
#! /bin/bash --
echo CODE: $CODE
echo SERVICE_RESULT: $SERVICE_RESULT
echo EXIT_CODE: $EXIT_CODE
echo EXIT_STATUS: $EXIT_STATUS
# systemctl cat sample_script.service
ExecStart=/bin/bash -c '/tmp/sample_script || /tmp/exit_handler $?'
Status of the sample_script.service:
# systemctl status sample_script.service
● sample_script.service - My service
Loaded: loaded (/etc/systemd/system/sample_script.service; enabled)
Active: inactive (dead) since Thu 2017-12-14 12:29:16 GMT; 7s ago
Process: 16511 ExecStopPost=/tmp/exit_handler (code=exited, status=0/SUCCESS)
Process: 16505 ExecStart=/bin/bash -c /tmp/sample_script || /tmp/exit_handler $? (code=exited, status=0/SUCCESS)
Main PID: 16505 (code=exited, status=0/SUCCESS)
Dec 14 12:29:11 build-local systemd: Started My service.
Dec 14 12:29:16 build-local bash: CODE: 255
Dec 14 12:29:16 build-local bash: SERVICE_RESULT:
Dec 14 12:29:16 build-local bash: EXIT_CODE:
Dec 14 12:29:16 build-local bash: EXIT_STATUS:
Dec 14 12:29:16 build-local exit_handler: CODE: N/A
Dec 14 12:29:16 build-local exit_handler: SERVICE_RESULT:
Dec 14 12:29:16 build-local exit_handler: EXIT_CODE:
Dec 14 12:29:16 build-local exit_handler: EXIT_STATUS:
You can see that
exit_handler has been called twice. At first from
bash where it has the exit code supplied to it and then as
ExecStopPost= script, where positional argument of exit code was not supplied therefore it printed N/A.