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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:20:31  来源:igfitidea点击:

How to make makefile exit with error when using a loop?

bashmakefile

提问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 breakcommand 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 exitwith 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