开发者

bash copy with variable

开发者 https://www.devze.com 2023-01-01 10:42 出处:网络
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.

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.tx开发者_如何学Ct      # not working as expected
echo cp $y x.txt # output is "cp /a/b/c\ d\ \(e\)\ f.txt x.txt"


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


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号