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

标签 bash quoting

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

打字时有效:

$ cd '/c/users/me/目录名称'

$ cd/c/users/me/dir\名称

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

$ 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)

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

最佳答案

用空格双引号您的路径变量,以保留它,

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

实际上,dirname 是一个内置的 shell,建议使用备用名称以避免与实际命令混淆。

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, ‘!’.

关于bash - 如何将带有空格的路径存储到 bash 中的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41995023/

相关文章:

linux - Bash 脚本进程替换语法错误 : "(" unexpected

bash - 在Jenkins管道文件的shell命令中转义双引号

bash - cd wslpath as bash function shell 引用问题

bash - 使用适当的引用自动重写 bash 脚本的工具?

linux - Grep 长度为 3 的行

regex - 当我匹配所有字符时在 SED 中转义 ~

mysql - 引用十进制值

linux - bash 中变量的空格和花括号

visual-studio-2010 - 如何在VS2010后期构建步骤中添加双引号

bash - 使用 bash 读取文本文件中行的子集