tags:

views:

506

answers:

2

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?

+2  A: 

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.

Adam Rosenfield
Ah thank you for the explanation!
nickf
+1  A: 

try:

dir="$HOME/path/to/$1/folder"
Joakim Elofsson
Just because Joakim provided no explanation at all: You had quoted the ~. ~ only expands in bash during tilde expansion, but anything that you quote, you disable the special meaning of, so the tilde (~) no longer meant "expands to the home directory of the current user". It just meant: "the directory in the current directory called ~". Which didn't exist, hence the error.
lhunath