Makefile中的条件语句是否为有效语法

时间:2016-03-11 03:51:49

标签: bash shell makefile

我有以下Makefile

~/w/i/craft-api git:develop ❯❯❯ cat Makefile                                                                                     ⏎ ✱ ◼
test:
    echo "TODO: write tests"
generate-toc:
    if ! [ -x "$(command -v doctoc)" ]; then
        echo "Missing doctoc. Run 'npm install doctoc -g' first"
    else
        doctoc ./README.md
    fi

我遇到了这个错误

~/w/i/craft-api git:develop ❯❯❯ make generate-toc                                                                                  ✱ ◼
if ! [ -x "" ]; then
/bin/sh: -c: line 1: syntax error: unexpected end of file
make: *** [generate-toc] Error 2

我的Makefile语法/用法有什么不正确?

编辑1

添加行继续反斜杠似乎无法解决问题:

~/w/i/craft-api git:develop ❯❯❯ cat Makefile                                                                                     ⏎ ✱ ◼
test:
    echo "TODO: write tests"
generate-toc:
    if ! [ -x "$(command -v doctoc)" ]; then \
      echo "Missing doctoc. Run 'npm install doctoc -g' first" \
    else \
        doctoc ./README.md \
    fi
~/w/i/craft-api git:develop ❯❯❯ make generate-toc                                                                                  ✱ ◼
if ! [ -x "" ]; then \
      echo "Missing doctoc. Run 'npm install doctoc -g' first" \
    else \
        doctoc ./README.md \
    fi
/bin/sh: -c: line 1: syntax error: unexpected end of file
make: *** [generate-toc] Error 2

1 个答案:

答案 0 :(得分:6)

每一行都被视为一个单独的命令,并传递给另一个shell实例。您可以使用\ continuation来组合所有行,因此make知道将它们作为一个长字符串传递给单个shell。这将删除换行符,因此您还需要在每个命令的末尾添加;

if ! [ -x "$$(command -v doctoc)" ]; then \
    echo "Missing doctoc. Run 'npm install doctoc -g' first"; \
else \
    doctoc ./README.md; \
fi

你也想要逃避$,否则make会解释它而不是shell。