.bashrc无法正确读取带有空格的环境路径

6
在我的Ubuntu 13中,我已经编辑了我的.bashrc文件,添加了一个环境路径:
export OGRE_ANDROID_ROOT=/home/piperoman/Librerias/Ogre\ Android\ SDK

如果我使用echo命令输出变量,它能正常工作,但是当我尝试在makefile中使用它时,就不起作用了。我已经使用cd命令测试过,结果如下:

$ echo $OGRE_ANDROID_ROOT 
/home/piperoman/Librerias/Ogre Android SDK
$ cd $OGRE_ANDROID_ROOT
bash: cd: /home/piperoman/Librerias/Ogre: No such file or directory

为什么echo命令可以正常工作,但是我无法正确地在其他命令中使用变量?

4个回答

10
Short-answer: 单词分割
当您有这个时。
export OGRE_ANDROID_ROOT=/home/piperoman/Librerias/Ogre\ Android\ SDK

环境变量包含"/home/piperoman/Librerias/Ogre Android SDK"。

如果您在不使用引号的情况下使用它,Bash将根据默认分割符(制表符、空格和换行符)将字符串拆分为单词。

因此

cd $OGRE_ANDROID_ROOT

等价于

cd "/home/piperoman/Librerias/Ogre" "Android" "SDK"

因此,您应该引用它,即 "$OGRE_ANDROID_ROOT"


3

只需在.bashrc中添加以下行,不需要反斜杠:

export OGRE_ANDROID_ROOT="/home/piperoman/Librerias/Ogre Android SDK"

当你想要使用变量进行 cd 时,请使用引号将其括起来:

cd "$OGRE_ANDROID_ROOT"

使用 export MYT="/home/me/test/my test/" 进行测试。


3

尝试

cd "$OGRE_ANDROID_ROOT" 

带引号。


1
@Piperoman,那个方法可行。你试过了吗?mkdir dir\ with\ spaces; var=dir\ with\ spaces,然后cd $var会显示bash: cd: dir: No such file or directory,但是cd "$var"则可以成功。 - glenn jackman
是的,我已经在GNU bash版本4.2.37(1)-release (x86_64-pc-linux-gnu)上进行了测试,但是使用了不同的路径,该路径也包含空格。 - Johannes P
问题出在导出:OGRE_ANDROID_ROOT="/home/piperoman/Librerias/Ogre Android SDK" 和 cd "$OGRE_ANDROID_ROOT" 是有效的。 - vgonisanz

1
:因为文件夹名称中间有空格。在Linux中,这些空格通常不会被用作单个文件夹的标识符。
例如:
$ mkdir hello\ world                    // will create a folder named hello world
$ cd hello\ world                      // go in to the created folder
$ pwd                                  // display the directory name

这将显示为hello>space<world
因此,环境变量$OGRE_ANDROID_ROOT被设置为/home/piperoman/Librerias/Ogre而不是/home/piperoman/Librerias/Ogre Android SDK。
为了解决这个错误,请重命名文件夹,以便去掉空格。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接