3

I have the following target in my makefile: (I'd like to run python http server in a detached process and when bash script is done kill the server)

TEST_PORT = 17777
test::
    $(ENV_VARS) \
    python -m SimpleHTTPServer $(TEST_PORT); \
    PID=$$(lsof -t -i @localhost:$(TEST_PORT) -sTCP:listen); \
    echo $(PID); \
    if [ -n "$$PID" ]; \
    then \
        python test.py; \
    fi; \
    function finish { \
        if [ -n "$$PID" ]; \
        then \
            kill -9 $$PID; \
        fi \
    } \
    trap finish EXIT;

However when I put a & after the line python ... I get an error

/bin/dash: Syntax error: ";" unexpected

How can this be done in a proper way?

EDIT

I have changed my makefile to do the following:

test::
    python -m SimpleHTTPServer $(TEST_PORT) &
    PID=$$(lsof -t -i @localhost:$(TEST_PORT) -sTCP:listen); \
        if [ -n "$$PID" ]; \
        then \
            $(ENV_VARS) python test.py; \
        fi \
        function finish { \
            if [ -n "$$PID" ]; \
            then \
                kill -9 $$PID; \
            fi \
        } \
        echo $$PID; \
        trap finish EXIT;

However I am getting an error: (without the line number)

/bin/dash: Syntax error: word unexpected

4

1 回答 1

2

这里要记住的重要一点是,当 shell 看到命令时,您的换行符实际上并不存在。

所以你的第一个命令变成:

$(ENV_VARS) python -m SimpleHTTPServer $(TEST_PORT); PID=$$(lsof -t -i @localhost:$(TEST_PORT) -sTCP:listen); echo $(PID); if [ -n "$$PID" ]; then python test.py; fi; function finish { if [ -n "$$PID" ]; then kill -9 $$PID; fi } trap finish EXIT;

你的第二个命令变成:

PID=$$(lsof -t -i @localhost:$(TEST_PORT) -sTCP:listen); if [ -n "$$PID" ]; then $(ENV_VARS) python test.py; fi function finish { if [ -n "$$PID" ]; then kill -9 $$PID; fi } echo $$PID; trap finish EXIT;

现在这些都很难阅读,所以我不希望您发现问题,但问题是您在一些地方缺少语句终止符。

具体来说:

  • 大括号 ( {}) 是单词元素,因此在它们周围需要空格(以及右大括号之前和之后的终止符)。fi } trap你在这里和这里都错过了那些终结者fi } echo

  • fi也不是语句终止符,因此它与下一条语句之间需要一个。您在这里缺少一个test.py; fi function(以及从第一点开始的括号中的那些)。

于 2015-07-21T12:22:28.527 回答