简体   繁体   English

如何从Shell脚本将字符串传递到Makefile?

[英]How to pass string to a makefile from shell script?

I tried in the following way 我尝试了以下方式

In shell script : 在shell脚本中:

Var='abc xyz' make one myvar=$Var

But when it goes into makefile it is just showing myvar as abc but it is not taking abc xyz as my input 但是当进入makefile文件时,它只是将myvar显示为abc但没有将abc xyz作为我的输入

Var='abc xyz' make one myvar=$Var

First of all, when expanding the Var variable in the line above, you may be expanding an undefined variable (ie: Var ). 首先,在上面的行中扩展Var变量时,您可能正在扩展未定义的变量 (即Var )。 What the line above is doing is just passing an environment variable called Var with that value to the process which is going to run make . 上面的代码行在做的只是将一个名为Var的环境变量传递给将要运行make的进程。

For the same reason, the following line may not print "Hello World" unless Var was previously defined with that value: 出于相同的原因,除非先前使用该值定义了Var ,否则以下行可能不会显示 “ Hello World”:

Var='Hello World' echo $Var

The following line will however display "Hello World": 但是,以下行将显示“ Hello World”:

Var='Hello World'; echo $Var

$Var in those examples above is being expanded by the shell. 上面的示例中的$Var由shell扩展。 The process running echo receives the Var variable, not the shell. 运行echo的进程将接收Var变量,而不是shell。


Back to the main problem 回到主要问题

But when it goes into makefile it is just showing myvar as abc but it is not taking abc xyz as my input 但是当进入makefile文件时,它只是将myvar显示为abc,但没有将abc xyz作为我的输入

The line 线

Var='abc xyz'; make one myvar=$Var

is being expanded by the shell as: shell正在将其扩展为:

Var='abc xyz'; make one myvar=abc xyz

The space above is used as separator for command-line arguments, so the process running make is actually receiving two arguments instead of one in place of the command-line variable: 上面的空间用作命令行参数的分隔符,因此运行make的进程实际上接收的是两个参数,而不是一个代替命令行变量的参数:

  1. myvar=abc
  2. xyz

Solution

You need to scape the space, so that it won't be interpreted as an argument separator by the shell. 您需要对空间进行转义,以免外壳将其解释为参数分隔符。 You can achieve that by placing double quotes around $Var : 您可以通过在$Var周围加上双引号来实现:

Var='abc xyz'; make one myvar="$Var"

This way, the process running make will receive a single argument for the command-line variable: myvar=abc xyz . 这样,运行make的进程将为命令行变量接收单个参数: myvar=abc xyz

Is there a reason you can't just pass it through the environment? 您是否有理由不能将其仅通过环境? Eg, 例如,

.PHONY: all
all: DEBUG

.PHONY: DEBUG
DEBUG:
        @echo $(test)

yields 产量

$ test="this is a test" make DEBUG
this is a test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM