Bash 在 Makefile 中扩展通配符

Tim*_*nes 17 bash make

我想对特定文件夹中不以特定前缀(例如exclude_)开头的所有文件进行操作。我有一个for带有扩展 glob的 bash循环,如下所示:

for FILE in foo/bar/!(exclude_*) ; do echo $FILE ; done
Run Code Online (Sandbox Code Playgroud)

在命令行上,这工作正常:

 $ for FILE in foo/bar/!(exclude_*) ; do echo $FILE ; done
 foo/bar/apple
 foo/bar/pear
 foo/bar/banana
Run Code Online (Sandbox Code Playgroud)

但是,当我在 makefile 中使用它时:

target:
    for FILE in foo/bar/!(exclude_*) ; do echo $$FILE ; done
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

$ make
for FILE in foo/bar/!(exclude_*) ; do echo $FILE ; done
/bin/sh: -c: line 0: syntax error near unexpected token `('
/bin/sh: -c: line 0: `for FILE in foo/bar/!(exclude_*) ; do echo $FILE ; done'
Run Code Online (Sandbox Code Playgroud)

是否有一些我错过的必要转义?

小智 12

使用 Make 而不是 Bash hacks 来解决这个问题会更惯用和更便携。如果有人没有安装 Bash 怎么办?

无论如何,这是在 Make 中执行此操作的正确方法

FOOFILES = $(filter-out foo/bar/exclude_%,$(wildcard foo/bar/*))

target:
    for FILE in ${FOOFILES}; do echo $$FILE ; done
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 9

  1. 您需要设置extglob.
  2. 您需要告诉 make 使用 bash,而不是 sh。

生成文件:

SHELL=/bin/bash
.SHELLFLAGS="-O extglob -c"
 ...
Run Code Online (Sandbox Code Playgroud)

  • 唔。出于某种原因,`.SHELLFLAGS` 对我不起作用,但将标志直接放在 `SHELL=/bin/bash -O extglob -c` 中。任何想法为什么? (2认同)