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 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

try:

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.