Reputation: 545985
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
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