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"

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.