gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:46:14 32 4
gpt4 key购买 nike

我想将 /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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com