I have a makefile rule in while I am executing a linux tool. I need to check the exit status of the tool command, and if that command fails the make has to be aborted.
I tried checking with $?, $$? \$? etc in the makefile. But they gives me syntax error when makefile runs.
What is the right way to do this ?
Here is the relevant rule in Makefile
mycommand \ if [ $$? -ne 0 ]; \ then \ echo "mycommand failed"; \ false; \ fi
Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.
The exit status of an executed command is the value returned by the waitpid system call or equivalent function. Exit statuses fall between 0 and 255, though, as explained below, the shell may use values above 125 specially. Exit statuses from shell builtins and compound commands are also limited to this range.
Explanation: The exit status of a command is that particular value which is returned by the command to its parent. This value is stored in $?. 6.
In the makefile-:
mycommand || (echo "mycommand failed $$?"; exit 1)
Each line in the makefile action invokes a new shell - the error must be checked in the action line where the command failed.
If mycommand fails the logic branches to the echo statement then exits.
Here are a couple of other approaches:
shell
& .SHELLSTATUS
some_recipe: @echo $(shell echo 'doing stuff'; exit 123) @echo 'command exited with $(.SHELLSTATUS)' @exit $(.SHELLSTATUS)
Output:
$ make some_recipe doing stuff command exited with 123 make: *** [Makefile:4: some_recipe] Error 123
It does have the caveat that the shell
command output isn't streamed, so you just end up with a dump to stdout when it finishes.
$?
some_recipe: @echo 'doing stuff'; sh -c 'exit 123';\ EXIT_CODE=$$?;\ echo "command exited with $$EXIT_CODE";\ exit $$EXIT_CODE
Or, a bit easier to read:
.ONESHELL: some_recipe: @echo 'doing stuff'; sh -c 'exit 123' @EXIT_CODE=$$? @echo "command exited with $$EXIT_CODE" @exit $$EXIT_CODE
Output:
$ make some_recipe doing stuff command exited with 123 make: *** [Makefile:2: some_recipe] Error 123
It's essentially one string of commands, executed in the same shell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With