从 bash 调用 m4 的参数数组

Array of arguments to call m4 from bash

我正在尝试动态计算用于调用 m4 的参数。但是我无法让引号中的字符串正常工作。

我正在尝试使用以下代码调用 m4 -DFOO="foo oh oh" sample.m4

test.sh:

#!/bin/bash
args=(-DFOO="foo oh oh")
m4 ${args[@]} sample.m4

样本.m4:

foo is FOO
bar is BAR

当我手动 运行 m4 命令时,它工作正常。当我使用我的测试脚本时,出现以下错误:

m4: cannot open `oh': No such file or directory
m4: cannot open `oh': No such file or directory
foo is foo
bar is BAR

很明显,它试图将字符串中的单词作为文件打开。如果我转义引号,我会收到此错误:

m4: cannot open `oh': No such file or directory
m4: cannot open `oh"': No such file or directory
foo is "foo
bar is BAR

如何让它正常工作?

总是引用你的 variable/array 扩展,除非你有理由不这样做(大多数情况下从来没有)

m4 "${args[@]}" sample.m4

未加引号的扩展导致数组中的单词被拆分,最终导致 m4 命令的参数数量不相等。