如何获取 GNU Makefile 中使用的 shell 命令的退出状态?

新手上路,请多包涵

在执行 linux 工具时,我有一个 makefile 规则。我需要检查 tool 命令的退出状态,如果该命令失败,则必须中止 make。

我试着用 \(?, \)\(? \\\)?等在makefile中。但是当makefile运行时它们给了我语法错误。

这样做的正确方法是什么?

这是Makefile中的相关规则

    mycommand \
    if [ $$? -ne 0 ]; \
    then \
        echo "mycommand failed"; \
        false; \
    fi

原文由 Lunar Mushrooms 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

在makefile中-:

 mycommand || (echo "mycommand failed $$?"; exit 1)

makefile 操作中的每一行都会调用一个新的 shell - 必须在命令失败的操作行中检查错误。

如果 mycommand 失败,则逻辑分支到 echo 语句然后退出。

原文由 suspectus 发布,翻译遵循 CC BY-SA 3.0 许可协议

以下是其他几种方法:


shell & .SHELLSTATUS

 some_recipe:
    @echo $(shell echo 'doing stuff'; exit 123)
    @echo 'command exited with $(.SHELLSTATUS)'
    @exit $(.SHELLSTATUS)

输出:

 $ make some_recipe

doing stuff
command exited with 123
make: *** [Makefile:4: some_recipe] Error 123

它确实有一个警告,即 shell 命令输出没有被流式传输,所以当它完成时你最终会转储到标准输出。


$?

 some_recipe:
    @echo 'doing stuff'; sh -c 'exit 123';\
    EXIT_CODE=$$?;\
    echo "command exited with $$EXIT_CODE";\
    exit $$EXIT_CODE

或者,更容易阅读:

 .ONESHELL:

some_recipe:
    @echo 'doing stuff'; sh -c 'exit 123'
    @EXIT_CODE=$$?
    @echo "command exited with $$EXIT_CODE"
    @exit $$EXIT_CODE

输出:

 $ make some_recipe

doing stuff
command exited with 123
make: *** [Makefile:2: some_recipe] Error 123

它本质上是一串命令,在同一个 shell 中执行。

原文由 c24w 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题