【问题标题】:Linux bash-script to run make in all subdirectoriesLinux bash-script 在所有子目录中运行 make
【发布时间】:2014-04-15 10:44:19
【问题描述】:

我正在尝试在 Linux 中编写一个 bash 脚本,它遍历当前目录,并在每个子目录中启动现有的 makefile。无论深度如何,它都应该适用于每个子目录。

一些限制:

  • 我无法使用 Python;
  • 我事先不知道有多少子目录及其名称;
  • 我事先不知道当前目录的名称;
  • 每个目录的make 命令只有在该文件夹中有makefile 时才应启动。

有什么想法吗?

【问题讨论】:

  • 你应该准确地展示你想要的东西......做例子然后告诉我们你到底想要什么
  • 我已尝试改进您的问题,使其更清晰。如果我改变了你帖子的意思,请编辑它。此外,正如 MortezaLSC 所指出的,添加一些您想要的示例,并向我们展示您迄今为止尝试过的内容。

标签: bash makefile


【解决方案1】:

使用 -exec 和 GNU

find -type f \( -name 'GNUmakefile' -o -name 'makefile' -o -name 'Makefile' \) \
-exec bash -c 'cd "$(dirname "{}")" && make' \;

【讨论】:

  • 谢谢。但我收到一条错误消息:line 2: -exec: command not found
  • 请注意,该命令没有换行符。您似乎在 -exec 之前有一个权利。
  • 如果我使用单个字符串find -type f -name 'GNUmakefile' -o -name 'makefile' -o -name 'Makefile' \ -exec bash -c 'cd $(dirname "{}"); make' \;,则会收到一条错误消息:find: paths must precede expression
  • @alex 确保您直接复制/粘贴它,或者只是删除Makefile 之后的转义字符并删除换行符。把它放在这里,这样它就可以在这里阅读了。
  • 非常感谢!是的,我只删除了第一个 \ 并使用单个字符串,然后它就可以工作了:find -type f -name 'GNUmakefile' -o -name 'makefile' -o -name 'Makefile' -exec bash -c 'cd $(dirname "{}"); make' \;
【解决方案2】:

鉴于这是与制造相关的。我会尝试在顶层使用 makefile 而不是脚本。像这样的:

MAKEFILES:=$(shell find . -mindepth 2 -name Makefile -type f)
DIRS:=$(foreach m,$(MAKEFILES),$(realpath $(dir $(m))))

.PHONY: all
all: $(DIRS)

.PHONY: $(DIRS)
$(DIRS):
     $(MAKE) -C $@

我会接受@MLSC 所说的关于将forfind 一起使用的说法,这种情况也适用于此。问题在于目录名称中有空格。但是,在许多情况下,这不会发生,恕我直言,使用 makefile 而不是脚本有好处。 (可能有一个使用 make 的解决方案可以处理目录名称中的空格,但我想不出来。)

【讨论】:

    【解决方案3】:

    你可以使用这个脚本https://gist.github.com/legeyda/8b2cf2c213476c6fe6e25619fe22efd0

    示例用法是:

    foreach */ 'test -f Makefile && make'
    

    【讨论】:

      【解决方案4】:

      如果不关心执行顺序或者父目录也有 Makefile,这应该可以工作。

      #!/bin/bash
      
      for f in $(find . -name Makefile); do
        pushd $(dirname $f)
        make
        popd
      done
      

      【讨论】:

      • for with find 不是一个好主意:find . -name Makefile | while IFS= read -r dir do . . . done
      • 谢谢。但我收到一条错误消息:line 1: syntax error near unexpected token do`
      • @MortezaLSC 如果我尝试使用字符串find . -name Makefile | while IFS= read -r dir do 而不是for f in $(find . -name Makefile); do,则会收到一条错误消息:line 1: syntax error near unexpected token 'done'
      • 您应该将代码放在一个文件中并从您的 shell 中运行它。
      • @tpatja 是的,我把它放在一个文件makeall.sh 中,但我得到了这个错误。
      猜你喜欢
      • 2022-08-18
      • 2013-07-03
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多