为什么波浪号 (~) 不在双引号内展开? [英] Why isn't tilde (~) expanding inside double quotes?

查看:51
本文介绍了为什么波浪号 (~) 不在双引号内展开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查隐藏的 .git 文件夹是否存在.首先想到的是使用:

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

但是 -d 显然不会查找隐藏文件夹.

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

推荐答案

问题与双引号内的波浪号有关.

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

或者,如hek2mgl在下面评论的那样,使用$HOME代替~:

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

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

来自 波浪号扩展中的 POSIX:

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 .

来自 双引号中的 POSIX:

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:

您可以在 为什么波浪号 (~) 不在双引号内展开? 中找到更多解释Unix &Linux 堆栈.

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

这篇关于为什么波浪号 (~) 不在双引号内展开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆