gpt4 book ai didi

bash - 无法在 makefile 中捕获命令退出代码

转载 作者:行者123 更新时间:2023-11-29 09:36:00 25 4
gpt4 key购买 nike

我正在尝试设置我的第一个 makefile 并在第 1 步遇到障碍。在我的 shell 脚本中,我这样做了:

which brew | grep 'brew not found' >/dev/null 2>&1
if [ $? == 0 ]; then
xcode-select --install
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi

这作为 bash 脚本工作得很好。经过一些谷歌搜索,对于 Makefile,我到目前为止想出了这个命令:

BREW_INSTALLED = $(shell which brew | grep 'brew not found' >/dev/null 2>&1; echo $$?)

但是,运行它会让我受益匪浅

make: BREW_INSTALLED: No such file or directory

我同样不确定何时应该将 @ 添加到命令(似乎是我不想输出的任何内容?)。

我目前正在使用 GNU Make 3.81

最佳答案

这一行有几种可能性:

BREW_INSTALLED = $(shell which brew | grep 'brew not found' >/dev/null 2>&1; echo $$?)

如果成功, 将其输出写入 stdout,如果失败则写入 stderr。您正在尝试在 stdout 上捕获错误消息。

要将 which 的 stderr 提供给 grep,您需要编写

which brew 2>&1 >/dev/null | grep 'brew not found'

(2>&1> 的顺序也很重要)。

但是你不应该依赖于which的具体错误信息。


但是您已经从 which 获得了您想要的返回码,所以您根本不需要 grep。

Which returns the number of failed arguments, or -1 when no `programname' was given. https://linux.die.net/man/1/which


考虑使用 grep -q 'expression' 来抑制输出而不是重定向 stdout 和 stderr。

-q, --quiet, --silent

Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. https://linux.die.net/man/1/grep


而且您收到的错误消息与我上面写的内容无关。这意味着 shell 正在尝试将 BREW_INSTALLED 作为命令运行,这可能意味着 make 将它放在新 shell 的开头。也许你是在制表符之后写的?见https://www.gnu.org/software/make/manual/html_node/Recipe-Syntax.html


要捕获返回码(作为字符串!):

BREW_INSTALLED := $(shell which brew >/dev/null 2>&1; echo $$?)

关于bash - 无法在 makefile 中捕获命令退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56996092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com