tags:

views:

36

answers:

2

I'm trying to copy files to the current directory using a bash script.

In order to handle paths that need escaping a variable is used that is escaped and then supplied to the cp command.

The cp command is complaining with:

usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file target_file
       cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file ... target_directory

I know what that means but I cannot understand why that happens.

Here is the code:

z="/a/b/c d (e) f.txt"
y=`printf %q "$z"`
cp $y x.txt      # not working as expected
echo cp $y x.txt # output is "cp /a/b/c\ d\ \(e\)\ f.txt x.txt"
+4  A: 

Note: When you are in trouble with a bash script, you should run it with the -x option as it provides a first level of debugging.

The escaping of the filename is incorrect. You should use:

cp "$z" x.txt
Laurent Etiemble
+2  A: 

You can avoid y altogether and use quotes:

cp "$z" x.txt

This is because tokenization occurs after variable substitution. Another possibility is to change the field separator:

IFS=""  # Set special variable denoting field separator (defaults to whitespace).
cp $y x.txt  # Works as you intended.
Stephen