【问题标题】:Makefile: write conditional statement for the shellMakefile:为shell编写条件语句
【发布时间】:2020-11-11 05:42:39
【问题描述】:

我使用this post 作为如何将参数传递给 make 目标的基础。

我想在这个命令行 arg 上执行字符串比较,使用 this post 作为在 makefile 中进行字符串相等比较的灵感。

更新使用以下建议的答案:

%:
    @:

test:
    if [ '$(filter-out $@,$(MAKECMDGOALS))' = hi ]; \
        echo "WON"; \
    else \
        echo "LOST"; \
    fi

我用 8 个空格代替缩进,没有打印。当我用制表符代替空格时,我收到以下错误:

if [ 'hi' = hi ]; \
        echo "WON"; \
    else \
        echo "LOST"; \
    fi
/bin/sh: -c: line 0: syntax error near unexpected token `else'
/bin/sh: -c: line 0: `if [ 'hi' = hi ];     echo "WON"; else    echo "LOST"; fi'
make: *** [test] Error 2

最初的尝试:

%:
        @:

test:
        ifeq ($(filter-out $@,$(MAKECMDGOALS)),hi)
                echo "WON"
        else
                echo "LOST"
        endif

但是,当我运行时,make test hi,我得到了

arg="hi"
ifeq (hi,hi)
/bin/sh: -c: line 0: syntax error near unexpected token `hi,hi'
/bin/sh: -c: line 0: `ifeq (hi,hi)'
make: *** [test] Error 2 

什么是意外令牌?

【问题讨论】:

    标签: bash makefile command-line-arguments


    【解决方案1】:

    ifeq 是一个 make 指令。通过使用 TAB 缩进它,您已将其放入配方中,并且配方中的所有命令都将传递给 shell。 shell 不知道ifeq 命令是什么,也无法理解这里的所有括号,所以会出现这些错误。

    如果你想对像 $@ 这样的自动变量进行条件化,它只在配方中可用,你必须编写一个 shell 条件语句,你不能使用 make 条件语句:

    test:
            if [ '$(filter-out $@,$(MAKECMDGOALS))' = hi ]; then \
                echo "WON"; \
            else \
                echo "LOST"; \
            fi
    

    【讨论】:

    • 我们需要做特殊的间距吗?当我运行 make test hi 时,什么也没有打印出来
    • 当我缩进 if/else 语句时,我得到 if [ 'hi' = hi ]; \ echo "WON"; \ else \ echo "LOST"; \ fi /bin/sh: -c: line 0: syntax error near unexpected token else' /bin/sh: -c: line 0: if [ 'hi' = hi ]; echo "WON"; else echo "LOST"; fi' make: *** [test] Error 2
    • 抱歉,忘记了然后
    【解决方案2】:

    留下这个答案作为发布的答案不起作用,因为它缺少then

    test:
            if [ '$(filter-out $@,$(MAKECMDGOALS))' = hi ]; then \
                echo "WON"; \
            else \
                echo "LOST"; \
            fi
    

    shell 条件转到 if [] then ... else ... fi

    【讨论】:

    • 省略 then 是 MadScientist 纠正的一个小错误;接受他的回答是合适的。
    猜你喜欢
    • 2021-06-30
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    相关资源
    最近更新 更多