Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:

    @A= $(ls)

...but it doesn't work.

share|improve this question

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


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 $$? )

    @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

Your Answer


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.