Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"grep THIS foo.txt > THIS.txt" gives an error in Makefile, not in bash, when grep output is empty

Tags:

grep

makefile

Makefile is as follows :

THIS.txt : foo.txt  
        grep THIS foo.txt > $@

When grep output is empty (no THIS in foo.txt), make gives an error message, bash does not :

$ make  
make:*** [THIS.txt] Error 1

$ grep THIS foo.txt > THIS.txt  

$ grep THIS foo.txt 2>&1  

How come? How should I modify my makefile to avoid an error message when grep output is empty?

like image 502
alxpublic Avatar asked Jan 21 '11 17:01

alxpublic


1 Answers

grep doesn't give an error in bash, but it does return a non-zero exit code:

> grep THIS foo.txt 2>&1
> echo $?
1

If you want to get rid of that non-zero exit code, so that make won't flag it as an error, you can do this:

THIS.txt : foo.txt
     grep THIS foo.txt > $@ || true

The || true bit says "if there is a nonzero exit code, return the exit code of true instead (which is always 0 in bash).

like image 196
Amber Avatar answered Sep 29 '22 09:09

Amber