2

我有下一个情况:test.mk
的来源:

test_var := test_me

test.sh的来源:

$test_var = some method that get test_var from .mk
if [ "$test_var" = "test_me" ] ; then    
   do something
fi

如何在没有其他解析技术的情况下从.mk文件获取变量到我的文件。.shgrep + sed

编辑
我无法更改.mk文件

4

4 回答 4

4

即时创建一个 makefile 以加载test.mk文件并打印变量:

value=$(make -f - 2>/dev/null <<\EOF
include test.mk
all:
    @echo $(test_var)
EOF
)

echo "The value is $value"
于 2012-12-18T16:42:09.683 回答
3

好吧,如果您不能使用sedor grep,那么您必须在使用以下内容进行解析后读取 makefile 数据库:

make -pn -f test.mk > /tmp/make.db.txt 2>/dev/null
while read var assign value; do
    if [[ ${var} = 'test_var' ]] && [[ ${assign} = ':=' ]]; then
        test_var="$value"
        break
    fi
done </tmp/make.db.txt
rm -f /tmp/make.db.txt

这可以确保类似:

value := 12345
test_var := ${value}

将输出12345,而不是${value}

如果您想创建代表 makefile 中所有变量的变量,您可以将内部 if 更改为:

if [[ ${assign} = ':=' ]]; then
    # any variables containing . are replaced with _
    eval ${var//./_}=\"$value\"
fi

所以你会得到像test_var设置为适当值的变量。有一些以 开头的 make 变量,.需要用 shell 变量的安全值替换,比如_,这就是 search-replace 正在做的事情。

于 2012-12-18T08:55:32.257 回答
2

print_var使用以下代码在您的 makefile 中创建规则:

print_var:
        echo $(test_var)

在你的test.sh,做:

 $test_var = $(make print_var)

您还必须考虑将print_var规则放在.PHONY部分

于 2012-12-18T08:02:12.207 回答
2

我前段时间自己提出的@Idelic答案的变体:

function get_make_var()
{
    echo 'unique123:;@echo ${'"$1"'}' | 
      make -f - -f "$2" --no-print-directory unique123
}

test_var=`get_make_var test_var test.mk`

它使用了 GNU make 鲜为人知的特性——使用多个选项Makefile从命令行读取多个 s 的能力。-f

于 2015-12-15T09:28:11.190 回答