For the following lines in my Makefile I get the error

Syntax error: end of file unexpected (expecting "then")

Code:

if [ ! -d upload-api/app-router/ ] then
    git clone someRepo upload-api/app-router/
fi

I've tried with a semicolon after the brackets but I get still the same error

You need to put then in next line or use semicolon

if [ ! -d upload-api/app-router/ ] 
then

or

if [ ! -d upload-api/app-router/ ];then
  • 1
    Note that the spaces before and after ; are optional, if [ ! -d upload-api/app-router/ ];then (or any combination) is equally valid. – dessert Aug 21 at 8:50
  • 1
    Totally agree ... – papampi Aug 21 at 8:56

In the context of a makefile, I see two things.

First, you need a semicolon or newline before the then. Shell syntax for if looks like: if commands... ; then commands... ; fi (where any semicolon here can be replaced with a newline).

Second, when make executes a recipe, it runs each individual line of the recipe in a separate shell instance, and stops executing if any single line gives an error. Effectively, it's running:

sh -c 'if [ ! -d upload-api/app-router/ ]; then' &&
    sh -c 'git clone someRepo upload-api/app-router/' &&
    sh -c 'fi'

...which is a syntax error on the first line, with or without the semicolon, because the if is never finished.

So for a makefile recipe, you would need to let make know that it should treat the entire if ... fi block as one line. For instance, use backslashes for line continuation, and semicolons in the appropriate places since the shell won't see any line breaks.

my-target:
↦       if [ ! -d upload-api/app-router/ ] ; then \
↦           git clone someRepo upload-api/app-router/ ; \
↦       fi

This gets unwieldy pretty quickly, so my preferred solution is usually to put the shellscript in a separate file, then run that file from your recipe.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.