0

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

#!/bin/sh
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:

./my_script.sh
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?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Meetarp
  • 103

1 Answers1

3

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 ~:

target="${target/#\~/$HOME}"

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

pLumo
  • 22,565