bash 使用循环时如何使makefile退出并出错?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19436631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make makefile exit with error when using a loop?
提问by user48956
If I have the following bash command:
如果我有以下 bash 命令:
for i in ./ x ; do ls $i ; done && echo OK
"ls ./" is executed, and then "ls x", which fails (x is missing) and OK is not printed.
执行“ls ./”,然后执行“ls x”,失败(x 丢失)并且不打印 OK。
If
如果
for i in x ./ ; do ls $i ; done && echo OK
then even though "ls x" fails, because the last statement in the for loop succeeded, then OK is printed. This is a problem when using shell for loops in makefiles:
然后即使“ls x”失败,因为for循环中的最后一条语句成功,然后打印OK。在 makefile 中使用 shell for 循环时,这是一个问题:
x:
for i in $(LIST) ; do \
cmd $$i ;\
done
How can I make make fail if any of the individual executions of cmd fails?
如果 cmd 的任何单个执行失败,如何使 make 失败?
回答by Barmar
Use the break
command to terminate the loop when a command fails
break
当命令失败时使用命令终止循环
x:
for i in $(LIST) ; do \
cmd $$i || break ;\
done
That won't make the makefile abort, though. You could instead use exit
with a non-zero code:
但是,这不会使 makefile 中止。您可以改为使用exit
非零代码:
x:
for i in $(LIST) ; do \
cmd $$i || exit 1 ;\
done
回答by rashok
After executing the command, check for return value of that command using $?
, as its make file you need to use double $
. If its non zero, then exit with failure.
执行命令后,使用 来检查该命令的返回值$?
,作为它的生成文件,您需要使用 double $
。如果它非零,则退出失败。
x:
set -e
for i in $(LIST); do \
cmd $$i; \
[[ $$? != 0 ]] && exit -1; \
echo 'done'; \
done