为什么波浪号 (~) 不在双引号内展开?
Why isn't tilde (~) expanding inside double quotes?
我想检查隐藏的.git
文件夹是否存在。首先想到的是使用:
if [ -d "~/.git" ]; then
echo "Do stuff"
fi
但是 -d
显然不会查找隐藏文件夹。
问题与波浪号在双引号内有关。
要展开它,您需要将波浪号放在引号外:
if [ -d ~/".git" ]; then # note tilde outside double quotes!
echo "Do stuff"
fi
或者,或者,正如 hek2mgl 在下面评论的那样,使用 $HOME
而不是 ~
:
if [ -d "$HOME/.git" ]
来自 Tilde expansion 中的 POSIX:
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 .
来自 POSIX 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:
您可以在 Why doesn't the tilde (~) expand inside double quotes? from the Unix & Linux Stack 中找到进一步的解释。
我想检查隐藏的.git
文件夹是否存在。首先想到的是使用:
if [ -d "~/.git" ]; then
echo "Do stuff"
fi
但是 -d
显然不会查找隐藏文件夹。
问题与波浪号在双引号内有关。
要展开它,您需要将波浪号放在引号外:
if [ -d ~/".git" ]; then # note tilde outside double quotes!
echo "Do stuff"
fi
或者,或者,正如 hek2mgl 在下面评论的那样,使用 $HOME
而不是 ~
:
if [ -d "$HOME/.git" ]
来自 Tilde expansion 中的 POSIX:
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 .
来自 POSIX 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:
您可以在 Why doesn't the tilde (~) expand inside double quotes? from the Unix & Linux Stack 中找到进一步的解释。