在 bash 中使用带有 cp 的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14589639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:22:59  来源:igfitidea点击:

Using variable with cp in bash

linuxbashvariablescp

提问by Todd

The file returned will have spaces in the file name so I run the file name through sed to append quotes at the beginning and end. However, when I use $CF with cp it fails. If I manually echo $CF and use the resulting file in place of $CF it works just fine. What's the problem?

返回的文件将在文件名中包含空格,因此我通过 sed 运行文件名以在开头和结尾附加引号。但是,当我将 $CF 与 cp 一起使用时,它会失败。如果我手动回显 $CF 并使用生成的文件代替 $CF 它工作得很好。有什么问题?

CF=`ls -tr /mypath/CHS1*.xlsx | tail -1 | sed -e 's/^/"/g' -e 's/$/"/g'`
cp $CF "/mydest/myfile.xlsx"

回答by Carl Norum

You don't need to add the quotes like that (in fact, it probably won't work). Instead, just use them in the cpline:

您不需要添加这样的引号(实际上,它可能不起作用)。相反,只需cp在行中使用它们:

CF=$(ls -tr /mypath/CHS1*.xlsx | tail -1)
cp "$CF" "/mydest/myfile.xlsx"

I changed it from using backticks to the newer (and preferred) $()syntax.

我将它从使用反引号更改为更新的(和首选的$()语法。