I'm writing a bash script and in it I'm doing something like the following:

read -p "Enter target directory: " target_dir
cp some/file.txt $target_dir/exists/for/sure/

When I run this shell script I see and input:

Enter target directory: ~/my_dir

But I get the error/output:

cp: directory ~/my_dir/exists/for/sure/ does not exist

And, as I'm trying to make obvious: That directory 100% exists. i.e. I can run the following without receiving any error:

cd ~/my_dir/exists/for/sure/

What's going on here?


Problem is, that ~ is taken literally and not expanded when you type it as input for read.

Test it:

$ read target
$ ls $target
ls: cannot access '~': No such file or directory

(note, the quotes around ~)

Use this:

eval target=$target # unsafe

or better, but expands just ~:


or even better, do not type variables or alike into read in the first place.

Not the answer you're looking for? Browse other questions tagged or ask your own question.