Using variable with cp in bash

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

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

You do not need to add such quotes (in fact, probably this will not work). Instead, just use them in the cp line:

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

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

+11
source

All Articles