views:

791

answers:

3

Here's a snippet of code from a shell script I have written:

for src in $(find . -type f -maxdepth 1 \! -name ${deploy} \! -name gvimrc)
do
    src=$(basename ${src})
    dest="~/.${src}"
    copy="${src} -> ${dest}"
    cp $src $dest && echo -e "${ok} ${copy}" || echo -e "${fail} ${copy}"
done

For some reason, cp fails to execute. For example, in the case in which $src='bashrc', I get this error:

cp: ~/.bashrc: No such file or directory

I don't understand why this happens, though, because obviously, ~/.bashrc is the destination, not the source, so cp shouldn't care whether it exists or not. What exactly is going wrong?

+3  A: 

You have escaped the ~ and so it won't get expanded and cp doesn't know how to do it.

With

dest=~/".${src}"

bash should do it.

iny
The answer with the "3" votes UP is a bit more complete...
Keltia
+9  A: 

Try using $HOME instead of ~/ for your home directory.

dest="$HOME/.$src"

Also, you might want to put quotes around your $src and $dest variables if you have spaces in any of your file names.

cp "$src" "$dest" && echo -e "${ok} ${copy}" || echo -e "${fail} ${copy}"
sirlancelot
+6  A: 

"~" is not expanded to your home directory when appearing in double quotes like that. Use "${HOME}/.${src}" instead. Also consider using another approach that will work when filenames contain spaces (oh, i just have to think of all my silly mp3 files with their spaces in them!). Instead of doing

for src in $(find . -type f -maxdepth 1 \! -name ${deploy} \! -name gvimrc)
do
    # ...
done

Prefer

find . -type f -maxdepth 1 \! -name ${deploy} \! -name gvimrc | while read src
do
    # ...
done

So by combining @sirlancelots and my space fixes, we get:

find . -type f -maxdepth 1 \! -name ${deploy} \! -name gvimrc | while read src
do
    src=$(basename "${src}")
    dest="${HOME}/.${src}"
    copy="${src} -> ${dest}"
    cp "$src" "$dest" && echo -e "${ok} ${copy}" || echo -e "${fail} ${copy}"
done
Johannes Schaub - litb