带空格的 Shell 变量,引用单个命令行选项 [英] Shell variable with spaces , quoting for single command line option

查看:30
本文介绍了带空格的 Shell 变量,引用单个命令行选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Autoconf 脚本在文件名或路径名有空格时有问题.例如,

Autoconf scripts have trouble with a filename or pathname with spaces. For example,

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

结果(config.log):

results in (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 并不是通用的解决方案).

The compile command from ./configure is ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' and I am not able to modify this (I could perhaps, but working around autoconf in this way is not a general solution).

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

I think it comes down to getting a shell variable that contains spaces to be parsed as a single command line variable rather than split at spaces. The simplest shell example I can come up with is to create a file with spaces and attempt to list is with ls with a shell variable as the argument to 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 代码:

This works, but is illegal since in autoconf I can't modify the shell code:

$ ls "$file"
a b

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

None of the following attempts at quoting things work:

$ 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 变量扩展为单个命令行参数?

Is this impossible to accomplish in shell scripts? Is there a magical quoting that will expand a shell variable with spaces into a single command line argument?

推荐答案

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

You should try to set the $IFS environment variable.

来自 man bash(1):

from man bash(1):

IFS - 用于分词的内部字段分隔符扩展后并使用 read 内置将行拆分为单词命令.默认值为空格制表符换行符".

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 否则会发生奇怪的事情.

Don't forget to set $IFS back or strange things will happen.

这篇关于带空格的 Shell 变量,引用单个命令行选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆