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

标签 bash shell 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

最佳答案

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

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

您还需要对 $ 进行转义,否则 make 将解释它而不是 shell。

关于bash - Makefile 中的条件语句是否有效语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35931866/

相关文章:

objective-c - NSTask 没有从用户环境中获取 $PATH

linux - 对目录中的文件使用 rm

bash - 重命名目录中特定类型的所有文件

python - pygsheets 上次访问或上次修改时间戳

bash - Cygwin:使用包含 Windows 路径的路径变量(其中有一个空格)

bash - 如何从 C 执行 bash 命令?

Ruby 转义 ARGV 参数或字符串作为 shell 命令的参数

bash - shell脚本中的while循环条件

perl - cpan(1) 失败,返回 'Cannot allocate memory'

c - 为什么我的 C 编译器找不到一些头文件?