如何将带有空格的路径存储到bash中的变量中 [英] How to store a path with white spaces into a variable in bash
问题描述
我想将/c/users/me/dir name
存储到一个变量中,以将其传递给cd
系统调用.
I want to store /c/users/me/dir name
into a variable to pass it to cd
system call.
键入时有效:
$ cd '/c/users/me/dir name'
或
$ cd /c/users/me/dir\ name
但如果我将其存储将不起作用:
but does not works if I store it:
$ 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)
哪种是正确的存储方式?
Which is the right way to store it?
推荐答案
将路径变量用空格双引号,以保留它,
Double-quote your path variable with spaces, to preserve it,
dirName="/c/users/me/dir name"
cd "$dirName"
实际上,dirname
是内置的shell,推荐,它使用备用名称以避免与实际命令混淆.
Actually, dirname
is a shell built-in, recommend using an alternate name to avoid confusion with the actual command.
在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中的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!