如何使用Makefile中的shell命令 [英] How to use shell commands in Makefile
问题描述
我试图用其他命令LS
的结果(例如回声,rsync的):
I'm trying to use the result of ls
in other commands (e.g. echo, rsync):
all:
<Building, creating some .tgz files - removed for clarity>
FILES = $(shell ls)
echo $(FILES)
但我得到:
make
FILES = Makefile file1.tgz file2.tgz file3.tgz
make: FILES: No such file or directory
make: *** [all] Error 1
我已经使用试图呼应$$文件
,回声$ {FILES}
和回声$(文件)
,没有运气。
推荐答案
通过
FILES = $(shell ls)
缩进下方所有
这样,它是一个构建命令。因此,这扩大了 $(壳LS)
,然后尝试运行命令文件...
。
indented underneath all
like that, it's a build command. So this expands $(shell ls)
, then tries to run the command FILES ...
.
如果文件
应该是一个制作
变量,这些变量需要配方部分以外的部分被分配,例如:
If FILES
is supposed to be a make
variable, these variables need to be assigned outside the recipe portion, e.g.:
FILES = $(shell ls)
all:
echo $(FILES)
当然,这意味着文件
将被设置为从 LS输出
前< / em>的运行任何创建.tgz的文件的命令。 (虽然作为卡兹指出中的变量每次重新扩大,所以最终会包含.tgz的文件;有的化妆变种有文件:a。= ...
来避免这种情况,为了提高效率和/或正确性)
Of course, that means that FILES
will be set to "output from ls
" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ...
to avoid this, for efficiency and/or correctness.)
如果文件
应该是一个shell变量,你可以设置它,但你需要做的是在外壳偏东,没有空格,并引述:
If FILES
is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:
all:
FILES="$(shell ls)"
不过,每一行是由一个单独的shell中运行,所以这个变量将无法生存到下一行,这样的话,你必须马上使用它:
However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:
FILES="$(shell ls)"; echo $$FILES
这是所有有点傻,因为shell将展开 *
(等外壳水珠前pressions)为您的第一个地方,所以你可以
This is all a bit silly since the shell will expand *
(and other shell glob expressions) for you in the first place, so you can just:
echo *
作为你的shell命令。
as your shell command.
最后,作为一般规则(未真正适用于本实施例):如在注释世界语的音符,使用从 LS输出
不是完全可靠的(一些细节依赖于文件名,有时甚至 LS版本
;有的版本的 LS
尝试在某些情况下消毒输出)。因此, l0b0 和 idelic 注意,如果你使用GNU让你可以使用 $(通配符)
和 $(SUBST ...)
来完成内部做
本身(避免,在文件名字符怪异的问题的话)。 (在 SH
脚本,包括makefile文件的食谱部分,另一种方法是使用找... -print0 | xargs的-0
,以避免绊倒空格,换行,控制字符等)。
Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls
is not completely reliable (some details depend on file names and sometimes even the version of ls
; some versions of ls
attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard)
and $(subst ...)
to accomplish everything inside make
itself (avoiding any "weird characters in file name" issues). (In sh
scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0
to avoid tripping over blanks, newlines, control characters, and so on.)
这篇关于如何使用Makefile中的shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!