Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get exit status of a shell command used in GNU Makefile?

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 
like image 796
Lunar Mushrooms Avatar asked May 01 '13 08:05

Lunar Mushrooms


People also ask

How do I get exit status from last command?

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.

What is the exit status of command?

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.

What is the exit status of a command and where is it stored?

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.


2 Answers

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.

like image 127
suspectus Avatar answered Sep 22 '22 18:09

suspectus


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.

like image 37
c24w Avatar answered Sep 21 '22 18:09

c24w