views:

317

answers:

2

I have a bash script which generates an SCP command to execute. The relevant parts of the code look like this:

echo $COPY_CMD
$COPY_CMD

My output looks like this:

rascher@localhost:~/Desktop/video_final$ ./xfervids.sh 
scp "/media/My Book/PhotosVideos/Videos/18May2008Download/SD_VIDEO/PRG001/MOV056.MOD" [email protected]:./video_working/
[email protected]'s password: 
"/media/My: No such file or directory
Book/PhotosVideos/Videos/18May2008Download/SD_VIDEO/PRG001/MOV056.MOD": No such file or directory

However, when I take line 2 of my output: scp "/media/..., copy it, and paste it into the terminal, it works.

What am I doing wrong? I have tried escaping the space in "My Book" ("My\ Book"), putting two \ characters rather than one ("My\\ Book") but I can't get this to behave consistently. Help?

+5  A: 

You have to be excruciatingly careful when there are spaces in the path names.

In the context, you probably need:

eval $COPY_CMD

You don't need quotes around the variable this time.

Jonathan Leffler
Was completely unaware of the `eval` bash command. Thank you!
rascher
+4  A: 

You should read this discussion of how and why to avoid putting commands in variables and this discussion of the security implications of eval.

One reason you may want to use variables in this way is to log or display the actions taken by a script. Problems occur with being able to properly quote or escape spaces, etc., as you have discovered. One way to do what you may want is to use set -x and set +x to turn this type of output on and off at various points in your script.

Dennis Williamson
Probably overkill for my little home dvd-burning script, but good info nonetheless.
rascher