Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer 1

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

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 '$$?'. This is to tell make that $? is a variable in the shell and not a variable in the Makefile.

This should be it! below 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

PS 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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.