为什么波浪号(〜)不能用双引号引起来? [英] Why isn't tilde (~) expanding inside double quotes?

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

问题描述

我想检查隐藏的.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中的字幕扩展:

波浪号前缀"由单词开头的未加引号的字符组成,其后是单词中第一个未加引号的所有字符,如果没有则由单词中的所有字符组成.

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中的双引号:

用双引号(")括起来的字符应保留双引号内所有字符的文字值,但以下字符除外:美元符号,反引号和反斜杠:

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天全站免登陆