bash - 带空格的 Shell 变量,引用单个命令行选项

标签 bash shell autoconf

Autoconf 脚本在处​​理带空格的文件名或路径名时会遇到问题。例如,

./configure CPPFLAGS="-I\"/path with space\""

结果(config.log):

configure:3012: gcc  -I"/path with space"  conftest.c  >&5
gcc: with: No such file or directory
gcc: space": No such file or directory

来自 ./configure 的编译命令是 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' 我无法修改它(我也许可以,但是以这种方式解决 autoconf 并不是一个通用的解决方案。

我认为这归结为获取一个包含空格的 shell 变量,将其作为单个命令行变量进行解析,而不是按空格拆分。我能想出的最简单的 shell 示例是创建一个带空格的文件,并尝试使用 ls 将 shell 变量作为 ls 的参数列出:

$ touch "a b"
$ file="a b"
$ ls $file
ls: a: No such file or directory
ls: b: No such file or directory

这行得通,但是是非法的,因为在 autoconf 中我不能修改 shell 代码:

$ ls "$file"
a b

以下引用事物的尝试均无效:

$ file="\"a \"b"; ls $file
ls: "a: No such file or directory
ls: b": No such file or directory
$ file="a\ b"
$ file="a\\ b"
$ file="`echo \\"a b\\"`"

等等。

这在 shell 脚本中是不可能完成的吗?是否有神奇的引号可以将带空格的 shell 变量扩展为单个命令行参数?

最佳答案

您应该尝试设置 $IFS 环境变量。

来自 man bash(1):

IFS - The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is ''space tab newline''.

例如

IFS=<C-v C-m>  # newline
file="a b"
touch $file
ls $file

不要忘记设置 $IFS 否则会发生奇怪的事情。

关于bash - 带空格的 Shell 变量,引用单个命令行选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1724032/

相关文章:

c++ - 如何在 [action-if-true] 中执行多个操作

linux - autoconf/configure 在哪里寻找包含文件

perl - 我可以使用基于 ExtUtils::MakeMaker 的构建系统 "out of tree"构建 Perl 模块吗?

mysql - 错误: database is uninitialized and password option is not specified

Python stdout 重定向(特殊)

macos - 如何在 mac os x 系统中静默安装 dmg 文件(使用 shell 脚本)?

bash - 如何通过 ssh 检查目录是否存在并将结果返回到主机

linux - 如何在删除文件之前检查文件是否具有正确的前缀

linux - shell脚本中字符串中的单引号

ruby - Make Coderay (in Pry) 高亮评论