What is wrong with this if condition of a bash script

Viewed 61

I have Ubuntu 18.04 with ZSH installed. I have this bash script for checking if a directory exist.

Even though i have a directory called "~/.config", the condition is always negative. I can't seem to figure out what is wrong with my code.

setup.sh

#!/bin/bash

if [ -d "~/.config" ] ; then
  echo "Directory exist"
else
  echo "Does not exist"
fi

Made the file executable by using chmod +x ./setup.sh output is always Does not exist

2 Answers

Since you have written "~/.config" it will be treated as literal string. To allow for ~ shell expansions you need to leave it unquoted:

#!/bin/bash
if [ -d ~/.config ] ; then
  echo "Directory exist"
else
  echo "Does not exist"
fi

This is well explained by Bash Pitfals, 26. echo "~":

26. echo "~"

Tilde expansion only applies when '~' is unquoted. In this example echo writes '~' to stdout, rather than the path of the user's home directory.

Quoting path parameters that are expressed relative to a user's home directory should be done using $HOME rather than '~'. For instance consider the situation where $HOME is "/home/my photos".

"~/dir with spaces" # expands to "~/dir with spaces"
~"/dir with spaces" # expands to "~/dir with spaces"
~/"dir with spaces" # expands to "/home/my photos/dir with spaces"
"$HOME/dir with spaces" # expands to "/home/my photos/dir with spaces"`

In bash, double quotes ("...") suppress glob and related expansions, such as *, ~ and others.

Double quotes retain shell variable expansion; single quotes ('...') suppress both glob expansion and shell variable expansion. Thus, they are each useful in different contexts.

But in contexts where you need *, ~, and so forth to be meaningful, you need unquoted expressions. ... Just watch out, because unexpected things can happen due to expansion if you are not careful.

Related