echo
echo

Reputation: 799

What ~ is parsed to?

When I run following commands:

if [ -d "~/Desktop" ]; then echo "exists"; fi
if [ -d "/bin" ]; then echo "exists"; fi

The first command echoes nothing, and the second echoes "exists". Why "~" is not understood by bash? Seems

if [ -d ~/Desktop ]; then echo "exists"; fi
if [[ -d ~/Desktop ]]; then echo "exists"; fi

will work. Is it possible to use quote with ~? The shell is bash. Thanks!

Upvotes: 0

Views: 114

Answers (3)

NPE
NPE

Reputation: 500257

~ is not expanded inside quotes. Try

if [ -d "$HOME/Desktop" ]; then echo "exists"; fi

Upvotes: 5

Nishu Tayal
Nishu Tayal

Reputation: 20830

Try replacing ~ with $HOME. Tilde expansion only happens when the tilde is unquoted

Instead use :

if [ -d "$HOME/Desktop" ]; then echo "exists"; fi

Upvotes: 1

devnull
devnull

Reputation: 123458

In your case, i.e. "~/Desktop", the tilde doesn't get expanded as it is treated as a literal.

Use eval to expand:

dir="~/Desktop"
eval dir=$dir
if [ -d "$dir" ]; then echo "exists"; fi

Upvotes: 1

Related Questions