如何将带有空格的路径存储到 bash 中的变量中

How to store a path with white spaces into a variable in bash

我想将 /c/users/me/dir name 存储到一个变量中以将其传递给 cd 系统调用。

键入时有效:

$ cd '/c/users/me/dir name'

$ cd /c/users/me/dir\ name

但如果我存储它就不起作用:

$ dirname="'/c/users/me/dir name'"
$ cd $dirname
$ bash: cd: /c/users/me/dir: No such file or directory

相同的结果:

$ dirname=('/c/users/me/dir name')

$ dirname=(/c/users/me/dir\ name)

哪种存储方式才是正确的?

在使用 bash 变量时,您应该 double-quote 它以保持其状态。

x='/home/ps/temp/bla bla'
 cd $x      ### <----used without double quotes. 
sh: cd: /home/ps/temp/bla: No such file or directory


 cd "$x"    ### <---While using a bash variable you should double-quote it to presever its state.
 pwd
/home/ps/temp/bla bla

Double-quote 你的带空格的路径变量,要保留它,

dirName="/c/users/me/dir name"
cd "$dirName"

实际上,dirname是一个shell built-in,建议使用别名以避免与实际命令混淆。

来自 man bash 页面,

Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’.