nickf
nickf

Reputation: 545985

Strange error checking if directory exists with Bash script

Here's a bash script I'm working on:

dir="~/path/to/$1/folder"

if [ -d "$dir" ]; then
    # do some stuff
else
    echo "Directory $dir doesn't exist";
    exit 1
fi

and when I run it from the terminal:

> ./myscript.sh 123
Directory ~/path/to/123/folder doesn't exist

But that folder clearly does exist. This works normally:

> ls ~/path/to/123/folder

What am I doing wrong?

Upvotes: 2

Views: 2241

Answers (2)

Adam Rosenfield
Adam Rosenfield

Reputation: 400146

The problem is that bash performs tilde expansion before shell parameter substitution, so after it substitutes ~/path/to/folder for $dir, it doesn't try to expand the ~, so it looks for a directory literally named with a tilde in it, which of course doesn't exist. See section 3.5 of the bash manual for a more detailed explanation on bash's expansions.

Upvotes: 5

Joakim Elofsson
Joakim Elofsson

Reputation: 38186

try:

dir="$HOME/path/to/$1/folder"

Upvotes: 1

Related Questions