如何在Makefile中为变量赋值?

时间:2016-07-21 22:45:41

标签: makefile variable-assignment assign

在尝试测试Makefile中命令失败时(在本例中为jekyll build relative),变量$$?应该包含最后一个命令的退出代码。在测试中,此代码显示为127.但是,我想将其分配给变量LAST_EXIT,以便下一个if语句可以检查执行的命令是成功还是失败。

问题是LAST_EXIT永远不会收到分配的值,如下面的代码所示。关于如何解决这个问题的任何建议?

代码:

LAST_EXIT = 0

all:
    @echo "Building the website... Running command:"
    - jekyll build relative || LAST_EXIT=$$?
    - jekyll build relative || echo $$? and $(LAST_EXIT)
ifeq ($(LAST_EXIT), 0)
    #echo a message indicating success 

输出:

jekyll build relative || LAST_EXIT=$?
/bin/sh: jekyll: command not found
jekyll build relative || echo $? and 0
/bin/sh: jekyll: command not found
127 and 0

2 个答案:

答案 0 :(得分:0)

您的方法存在两个问题。

1)make make在执行任何规则之前解析makefile的条件部分。这样:

all:
    LAST_EXIT=0
ifeq ($(LAST_EXIT), 0)
    #echo a message indicating success 
endif

不会报告成功(除非您在规则之上的某处设置LAST_EXIT的值)。

2)配方中的每个命令都在自己的子shell中执行; shell变量值从一行保存到下一行:

all:
    LAST_EXIT=5; echo the value is $$LAST_EXIT
    @echo now the value is $$LAST_EXIT

这应该有效:

all:
    - jekyll build relative || LAST_EXIT=$$?; \
  if [ $$LAST_EXIT == 0 ]; then  echo success!; fi

答案 1 :(得分:0)

我对此问题的解决方法是在Makefile中调用以下脚本来检查Jekyll: (称为./{scriptName}

#!/bin/bash

LINEBREAK="*****************************************************************"
VERSION=0

echo "Checking Jekyll..."
VERSION=$(jekyll --version)

if test "$?" == "0"
then
     echo "$VERSION is installed on this system..."
else
     echo "$LINEBREAK"
     echo "Oops! It looks like you don't have Jekyll yet, lets install it!"
     echo "Running command: \"sudo gem install jekyll\""
     echo "$LINEBREAK"
     sudo gem install jekyll
     if test "$?" != "0"
     then
          echo "$LINEBREAK"
          echo "Jekyll install failed... It needs to be installed as a super-user on your system, which"
          echo "requires your password. You can run \"sudo gem install jekyll\" yourself to install Jekyll."
          echo "You can also see their website at: \"https://jekyllrb.com/docs/installation/\" for more information"
          echo "$LINEBREAK"
          exit 113
     else
          echo "$LINEBREAK"
          echo "Jekyll has been installed on this system..."
          echo "Proceeding to build..."
          echo "$LINEBREAK"
     fi
fi

exit 0