Why isn't tilde (~) expanding inside double quotes? [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-26 04:28:58

问题


I want to check whether or not the hidden .git folder exists. First thought was to use:

if [ -d \"~/.git\" ]; then
   echo \"Do stuff\"
fi

But the -d apparently does not look for hidden folders.


回答1:


The problem has to do with the tilde being within double quotes.

To get it expanded, you need to put the tilde outside the quotes:

if [ -d ~/".git" ]; then   # note tilde outside double quotes!
   echo "Do stuff"
fi

Or, alternatively, as commented below by hek2mgl, use $HOME instead of ~:

if [ -d "$HOME/.git" ]

From POSIX in Tilde expansion:

A "tilde-prefix" consists of an unquoted character at the beginning of a word, followed by all of the characters preceding the first unquoted in the word, or all the characters in the word if there is no .

From POSIX in Double Quotes:

Enclosing characters in double-quotes ( "" ) shall preserve the literal value of all characters within the double-quotes, with the exception of the characters dollar sign, backquote, and backslash, as follows:

You can find further explanations in Why doesn't the tilde (~) expand inside double quotes? from the Unix & Linux Stack.



来源:https://stackoverflow.com/questions/41871596/why-isnt-tilde-expanding-inside-double-quotes

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