6

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Swifting
  • 449
  • 1
  • 5
  • 19

1 Answers1

12

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 <tilde> character at the beginning of a word, followed by all of the characters preceding the first unquoted <slash> in the word, or all the characters in the word if there is no <slash>.

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.

MicroVirus
  • 5,324
  • 2
  • 28
  • 53
fedorqui
  • 275,237
  • 103
  • 548
  • 598