Bash: Makefile 中的 for 循环: 意外的文件结尾

Bash: for loop in Makefile: unexpected end of file

我正在编写一个 Makefile,它将列出 a.cpp、b.cpp 和 c.h 文件包含的所有 headers。但是,我得到了意外的 EOF 错误。类似的问题总是由行终止符引起的,比如他们使用 CRLF 而不是 LF 来表示 EOL。但是,我的文本编辑器设置为使用 LF,我通过删除所有 EOL 和 re-added 重新检查了这一点。不幸的是,错误仍然存​​在。以下是代码:

#!/bin/bash

list-header:
    for file in a.cpp b.cpp b.h
    do
        echo "$file includes headers: "
        grep -E '^#include' $file | cut -f2
    done

我收到此错误消息:

for file in "Bigram.cpp client.cpp Bigram.h"
/bin/sh: -c: line 1: syntax error: unexpected end of file"

在此先感谢您的帮助。

首先请注意,您必须转义要让 shell 看到的 $,否则 make 会在调用 shell 之前展开它们。但是,您的主要问题是 make 配方中的每个逻辑行都是一个单独的 shell 命令。所以,这个规则:

list-header:
        for file in a.cpp b.cpp b.h
        do
            echo "$file includes headers: "
            grep -E '^#include' $file | cut -f2
        done

将导致 make 调用 shell 命令:

/bin/sh -c 'for file in a.cpp b.cpp b.h'
/bin/sh -c 'do'
/bin/sh -c 'echo "ile includes headers: "'
/bin/sh -c 'grep -E '^#include' ile | cut -f2'
/bin/sh -c 'done'

如果您希望将它们全部发送到同一个 shell,则需要使用反斜杠 "continue" 跨换行符的逻辑行,并且您必须添加分号才能使其正常工作,因为换行符没有不再用作命令分隔符:

list-header:
        for file in a.cpp b.cpp b.h; \
        do \
            echo "$$file includes headers: "; \
            grep -E '^#include' $$file | cut -f2; \
        done