1

As part of a bash script, which has set -e, I do make distclean which, obviously, fails with the following error, if I have run distclean before calling the script:

make: *** No rule to make target 'distclean'. Stop

Is there way to do distclean and not fail if there's nothing to clean?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Kap4Lin
  • 109
  • 5
  • You need to provide more details. What is distclean? Is it some custom command, what does it do? – kiner_shah Jan 04 '22 at 04:11
  • 1
    @kiner_shah It's a common target with Autotools projects. See https://www.gnu.org/prep/standards/html_node/Standard-Targets.html#Standard-Targets. In a common `./configure && make && make install` setup `make distclean` will delete the `Makefile`, leaving only the `configure` script behind, which leads to the error in the question. – John Kugelman Jan 04 '22 at 04:30
  • Do the answers to ["How to undo the effect of `set -e` which makes bash exit immediately if any command fails?"](https://stackoverflow.com/questions/3517162/how-to-undo-the-effect-of-set-e-which-makes-bash-exit-immediately-if-any-comm) and ["Bash ignoring error for a particular command"](https://stackoverflow.com/questions/11231937/bash-ignoring-error-for-a-particular-command) answer your question? – Gordon Davisson Jan 04 '22 at 04:59
  • Avoiding `set -e` and adding your own fail messages is also better. – konsolebox Jan 04 '22 at 06:39

2 Answers2

2

If you're okay with the error message being printed, and just want to ignore the failure and keep going, a common idiom is to append || :.

The general syntax here is cmd1 || cmd2. If cmd1 fails then it runs cmd2. : is the (unusual) name of a command that always succeeds, so || : has the effect of ignoring the first command's exit code.

make distclean || :

If you would rather not see an error message at all, you could check if the Makefile exists first:

if [[ -e Makefile ]]; then make distclean; fi
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Error message can also be ignored with `2>/dev/null` or `>/dev/null 2>&1` if not enough. – konsolebox Jan 04 '22 at 06:38
  • 2
    As the `Makefile` is both the most characteristic artifact of having configured (and not dist-cleaned) the project and also the file whose absence is most directly related to the error, testing for the presence of that file before executing `make distclean` seems exactly the right thing to do to avoid the error the OP describes. – John Bollinger Jan 04 '22 at 15:43
  • 1
    I do not want to swallow an unknown error with `||`. I will prefer the `-e Makefile ` option. Thanks John. – Kap4Lin Jan 04 '22 at 19:51
0

You could do a

make distclean || echo "(Error from make ignored)"

to make it explicit what's happening.

user1934428
  • 19,864
  • 7
  • 42
  • 87