Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script to copy files from one directory to another

Trying to write a simple script to copy some files in OS X 10.9. Here's the content..

SRC_DIR="~/Library/Preferences-Old"

DST_DIR="~/Library/Preferences"

FILEN="test.txt"

cp $SRC_DIR/$FILEN $DST_DIR

Gives me the output:

cp: ~/Library/Preferences-Old/test.txt: No such file or directory

Of course, the above is wrong. The exact same cp command in terminal directly does the trick. What am I doing wrong here?

like image 802
apil.tamang Avatar asked Dec 04 '22 03:12

apil.tamang


2 Answers

~ is one of the few exceptions to the rule "When in doubt, quote". As others have pointed out, a quoted ~ is not subject to expansion. However, you can still quote the rest of the string:

SRC_DIR=~"/Library/Preferences-Old"
DST_DIR=~"/Library/Preferences"

Note that depending on the values assigned to the two *_DIR variables, it's not enough to quote the values being assigned; you still need to quote their expansions.

FILEN="test.txt"

cp "$SRC_DIR/$FILEN" "$DST_DIR"
like image 60
chepner Avatar answered Dec 06 '22 15:12

chepner


Your double-quotes are preventing the shell from converting your ~ into an actual path. Observe:

$ echo ~
/home/politank_z

$ echo "~"
~

~ isn't an actual location, it is shorthand for the path of your home directory.

like image 22
Politank-Z Avatar answered Dec 06 '22 16:12

Politank-Z