[ACCEPTED]-Shell status codes in make-makefile

Accepted answer
Score: 38

I think you're looking for the $? shell variable, which 11 gives the exit code of the previous command. For 10 example:

$ diff foo.txt foo.txt
$ echo $?

To use this in your makefile, you 9 would have to escape the $, as in $$?:

    diff foo.txt foo.txt ; if [ $$? -eq 0 ] ; then echo "no differences" ; fi

Do note 8 that each command in your rule body in make 7 is run in a separate subshell. For example, the 6 following will not work:

    diff foo.txt foo.txt
    if [ $$? -eq 0 ] ; then echo "no differences" ; fi

Because the diff and 5 the if commands are executed in different 4 shell processes. If you want to use the 3 output status from the command, you must 2 do so in the context of the same shell, as 1 in my previous example.

Score: 4

Use '$$?' instead of '$$!' (thanks to 4th 1 answer of Exit Shell Script Based on Process Exit Code)

Score: 4

Don't forget that each of your commands 8 is being run in separate subshells.

That's 7 why you quite often see something like:

    do something \
    do something else \
    do last thing.

And 6 when debugging, don't forget the every helpful 5 -n option which will print the commands 4 but not execute them and the -p option which 3 will show you the complete make environment 2 including where the various bits and pieces 1 have been set.



Score: 2

If you are passing the result code to an 1 if, you could simply do:

    if diff foo.txt foo.txt ; then echo "no differences" ; fi
Score: 0

The bash variable is $?, but why do you want 1 to print out the status code anyway?

More Related questions