bash 路径中的波浪号不会扩展到主目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5748216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tilde in path doesn't expand to home directory
提问by Benjamin
Say I have a folder called Foolocated in /home/user/(my /home/useralso being represented by ~).
假设我有一个名为的文件夹Foo位于/home/user/(我的/home/user也由 表示~)。
I want to have a variable
我想要一个变量
a="~/Foo"and then do
a="~/Foo"然后做
cd $a
cd $a
I get
-bash: cd: ~/Foo: No such file or directory
我得到
-bash: cd: ~/Foo: No such file or directory
However if I just do cd ~/Fooit works fine. Any clue on how to get this to work?
但是,如果我只是这样做,cd ~/Foo它就可以正常工作。有关如何使其工作的任何线索?
回答by bmk
You can do (without quotes during variable assignment):
你可以这样做(在变量赋值期间没有引号):
a=~/Foo
cd "$a"
But in this case the variable $awill not store ~/Foobut the expanded form /home/user/Foo. Or you could use eval:
但在这种情况下,变量$a将不会存储,~/Foo而是扩展形式/home/user/Foo。或者你可以使用eval:
a="~/Foo"
eval cd "$a"
回答by user268396
You can use $HOMEinstead of the tilde (the tilde is expanded by the shell to the contents of $HOME).
Example:
您可以使用$HOME代替波浪号(波浪号由外壳扩展为 的内容$HOME)。例子:
dir="$HOME/Foo";
cd "$dir";
回答by khamer
A much more robust solution would be to use something like sed or even better, bash parameter expansion:
一个更强大的解决方案是使用类似 sed 甚至更好的 bash 参数扩展:
somedir="~/Foo/test~/ing";
cd ${somedir/#\~/$HOME}
or if you must use sed,
或者如果你必须使用 sed,
cd $(echo $somedir | sed "s#^~#$HOME#")
回答by danron
If you use double quotes the ~ will be kept as that character in $a.
如果您使用双引号, ~ 将作为该字符保留在 $a 中。
cd $a will not expand the ~ since variable values are not expanded by the shell.
cd $a 不会扩展 ~ 因为变量值不会被 shell 扩展。
The solution is:
解决办法是:
eval "cd $a"
评估“cd $a”

