Bash: for loop in Makefile: unexpected end of file

I am writing a Makefile that will list all the headers included in files a.cpp, b.cpp and ch However, I got an unexpected EOF error. Questions like this are always caused by the line terminator, as they used CRLF instead of LF for EOL. However, my text editor was set to use LF and I double-check that by removing all EOLs and re-adding. Unfortunately, the error still persists. Here are the codes:

#!/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 your help.

+3


source to share


1 answer


First of all, you need to escape from $

what you want to see in the shell, otherwise make will expand them before calling the shell. However, the main problem is that each logical line in a make recipe is a separate shell command. So this is the rule:

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

      

will force make to invoke shell commands:



/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 a backslash to continue the boolean line on new lines if you want them all to be sent to the same shell and you have to add semicolons to make this work as newlines no longer serve as command separators:

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

      

+10


source







All Articles