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

给你一囗甜甜゛ 提交于 2019-12-02 03:11:32

问题


I want to store /c/users/me/dir name into a variable to pass it to cd system call.

Works when typing:

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

or

$ 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

the same result to:

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

or

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

Which is the right way to store it?


回答1:


Double-quote your path variable with spaces, to preserve it,

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

Actually, dirname is a shell built-in, recommend using an alternate name to avoid confusion with the actual command.

From the man bash page,

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




回答2:


While using a bash variable you should double-quote it to preserve its state.

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


来源:https://stackoverflow.com/questions/41995023/how-to-store-a-path-with-white-spaces-into-a-variable-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!