Basic if else statement in Makefile

后端 未结 3 1704
灰色年华
灰色年华 2020-12-21 09:52

I\'m trying to execute a simple if else statement in a Makefile:

check:
  if [ -z \"$(APP_NAME)\" ]; then \\
    echo \"Empty\" \\
  else \\
    echo \"Not e         


        
3条回答
  •  [愿得一人]
    2020-12-21 10:22

    Change your version to this (adding semicolons):

    check:
        if [ -z "$(APP_NAME)" ]; then \
            echo "Empty"; \
        else \
            echo "Not empty"; \
        fi
    

    For evaluating a statement in shell without newline (newline gets eaten by the backslash \) you need to properly end it with a semicolon. You cannot use real newlines in a Makefile for conditional shell-script code (see Make-specific background)

    [ -z "$(APP_NAME)" ], echo "Empty", echo "Not empty" are all statements that need to be evaluated (similar to pressing enter in terminal after you typed in a command).

    Make-specific background

    make spawns a new shell for each command on a line, so you cannot use a true multiline shell code as you would e.g. in a script-file.

    Taking it to an extreme, this would be possible in a shell script file, because the *newline** acts as command-evaluation (like in the terminal hitting enter is a newline-feed):

    if
    [ 0 ]
    then
    echo "Foo"
    fi
    

    Listing 1

    If you would write this in a Makefile though, if would be evaluated in its own shell (changing the shell-state to if) after which technically the condition [ 0 ] would be evaluated in its own shell again without any connection to the previous if. Although make will not even get past the first if because it expects an exit code to go on to the next statement, which it will not get from just changing the shell's state to if.

    In other words if two commands in a make-target are completely independent of each other (no conditions what so ever) you could just perfectly fine seperate them only by a normal newline and let them execute each in its own shell.

    So in order to make make to correctly evaluate multiline conditional shell scripts, you need to evaluate the whole shell-script-code in one line (so it all is evaluated in the same shell).

    So for working correctly in a Makefile the code in Listing 1 needs to be translated to:

    if \
    [ 0 ]; \
    then \
    echo "Foo"; \
    fi
    

    The last command fi does not need the backslash because that's where we don't need to keep the spawned shell open anymore.

提交回复
热议问题