Tilde in path doesn't expand to home directory

匆匆过客 提交于 2019-12-16 21:32:33

问题


Say I have a folder called Foo located in /home/user/ (my /home/user also being represented by ~).

I want to have a variable

a="~/Foo" and then do

cd $a

I get -bash: cd: ~/Foo: No such file or directory

However if I just do cd ~/Foo it works fine. Any clue on how to get this to work?


回答1:


You can do (without quotes during variable assignment):

a=~/Foo
cd "$a"

But in this case the variable $a will not store ~/Foo but the expanded form /home/user/Foo. Or you could use eval:

a="~/Foo"
eval cd "$a"



回答2:


You can use $HOME instead of the tilde (the tilde is expanded by the shell to the contents of $HOME). Example:

dir="$HOME/Foo";
cd "$dir";



回答3:


A much more robust solution would be to use something like sed or even better, bash parameter expansion:

somedir="~/Foo/test~/ing";
cd ${somedir/#\~/$HOME}

or if you must use sed,

cd $(echo $somedir | sed "s#^~#$HOME#")



回答4:


If you use double quotes the ~ will be kept as that character in $a.

cd $a will not expand the ~ since variable values are not expanded by the shell.

The solution is:

eval "cd $a"



来源:https://stackoverflow.com/questions/5748216/tilde-in-path-doesnt-expand-to-home-directory

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