Using variable with cp in bash

21,339

You don't need to add the quotes like that (in fact, it probably won't 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 newer (and preferred) $() syntax.

Share:
21,339
Todd
Author by

Todd

Full-stack developer (NodeJS) Used to be very shy which made be a good learner but life sucked. A year of ToastMasters turned my life around.

Updated on July 05, 2022

Comments

  • Todd
    Todd almost 2 years

    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?

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