我有一个 Makefile,想要调用另一个外部的 bash 脚本来完成构建的另一部分。我该如何最好地完成这个操作?
就像从 makefile 调用其他命令一样:
target: prerequisites
shell_script arg1 arg2 arg3
关于您进一步的解释:
.PHONY: do_script
do_script:
shell_script arg1 arg2 arg3
prerequisites: do_script
target: prerequisites
也许不是像已经提供的答案那样做事情的“正确”方式,但我遇到了这个问题,因为我希望我的makefile运行我编写的脚本来生成一个头文件,为整个软件包提供版本。我在这个软件包中有很多目标,并且不想向它们所有添加全新的先决条件。将此放在我的makefile开头对我有用。
$(shell ./genVer.sh)
这告诉make只需运行一个shell命令。 ./genVer.sh
是要运行的脚本路径(与makefile同一目录)和名称。无论我指定哪个目标(包括clean
),它都会运行,这是��点,但对我来说并不是很重要。
Makefile规则中的每个动作都是将在子shell中执行的命令。你需要确保每个命令都是独立的,因为每个命令都将在单独的子shell中运行。
出于这个原因,当作者想要多个命令在同一个子shell中运行时,你经常会看到换行符被转义:
targetfoo:
command_the_first foo bar baz
command_the_second wibble wobble warble
command_the_third which is rather too long \
to fit on a single line so \
intervening line breaks are escaped
command_the_fourth spam eggs beans
目前我使用Makefile,可以很容易地调用bash脚本,例如:
Currently using Makefile, I can easily call the bash script like this:
dump:
./script_dump.sh
并且呼叫:
make dump
这也像其他答案中提到的那样工作:
dump:
$(shell ./script_dump.sh)
但是缺点是,除非你将命令存储在变量中并使用echo
命令输出,否则你无法从控制台获取Shell命令。
不确定这是否是最佳实践,但我发现最直接的方法是使用bash
,如果您的终端支持它:
run_file:
bash ./scripts/some_shell_script.sh
这样做可以避免先更改文件权限,然后通过直接执行即 ./scripts/some_shell_script.sh
的方式来执行。或者,为了在生成的 make 进程中使用 source 命令,下面的两种方法也可以使用(./
是可选的)。
run_file_source:
source ./scripts/some_shell_script.sh
run_file_source_alt:
. ./scripts/some_shell_script.sh
在您的终端中,可以运行以下命令。
$ make run_file
在运行shell脚本激活虚拟环境后(通过使用&&
链接命令),扩展make条目以运行Python文件:
run-python:
@bash -c "source ./scripts/python/activate_env.sh && \
python src/python_scripts/main.py"
run-python-alt:
@source ./scripts/python/activate_env.sh && \
python src/python_scripts/main.py
.PHONY
目标,并使你的先决条件依赖于该目标,在该目标中运行脚本。 - Carl Norum