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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30412874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:02:13  来源:igfitidea点击:

Bash: for loop in Makefile: unexpected end of file

bashmakefile

提问by Baozi CAI

I am writing a Makefile, which will list all headers included by a.cpp, b.cpp and c.h files. However, I got the error of unexpected EOF. Similar questions are always caused by the line terminator, like they used CRLF instead of LF for an EOL. However, my Text editor was set to using LF and I recheck this by delete all EOL and re-added. Unfortunately, the error still remains. Here are the codes:

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

#!/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

I got this error message:

我收到此错误消息:

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

Thanks in advance for any help.

在此先感谢您的帮助。

回答by MadScientist

First note you have to escape $that you want the shell to see, otherwise make will expand them before calling the shell. However, your main problem is that every logical line in a make recipe is a separate shell command. So, this rule:

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

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

will cause make to invoke the shell commands:

将导致 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'

You need to use backslashes to "continue" a logical line across newlines if you want them all sent to the same shell, and you have to add semicolons to make that work since the newlines no longer serve as command delimiters:

如果您希望将它们全部发送到同一个 shell,您需要使用反斜杠在换行符之间“继续”逻辑行,并且您必须添加分号才能使其工作,因为换行符不再用作命令分隔符:

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