3

I'm trying to save the standard exit status of a command in a variable of my makefile, but I don't know how to do it.

I've tried this:

pruebas:
    @A= $(ls)

...but it doesn't work.

1 Answer 1

5

You can execute a command in the shell from the Makefile by using the $(shell command) syntax. If for instance you would want to exit status of the ls command in bash you would type:

ls --qwfpgjl > /dev/null 2>&1 ; echo $?

This might need some explanation: the > /dev/null 2>&1 part redirects both standard output and standard error to /dev/null so you don't see any output, and then 'echo $?' prints the exit status of the last command. You can try this in the command line to see if it works for you, for instance

ls --qwfpgjl > /dev/null 2>&1 ; echo $?

should give you

2

since that is the error ls returns when there is an unknown argument (see the ls man page).

Now how to include this in your Makefile? Simply add the line

A=$(shell ls > /dev/null 2>&1 ; echo $$?)

to your Makefile. Note the extra $ in $$?, it tells make that $? is not a variable in the Makefile.

That should be it! Here you can see the Makefile I used to test this behavior:

#SHELL := /bin/bash
A=$(shell ls > /dev/null 2>&1 ; echo $$? )

test:
    @echo $A
.PHONY: test

Notes:
make picks the /bin/sh shell by default, but you can override this by setting

SHELL := /bin/bash

This can be useful for more complicated commands that don't execute in /bin/sh.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .