Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable with cp in bash

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"
like image 324
Todd Avatar asked Jan 29 '13 18:01

Todd


People also ask

What is CP in bash script?

cp stands for copy. This command is used to copy files or group of files or directory. It creates an exact image of a file on a disk with different file name. cp command require at least two filenames in its arguments.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

What does $# do in bash?

$# is typically used in bash scripts to ensure a parameter is passed. Generally, you check for a parameter at the beginning of your script. To summarize $# reports the number of parameters passed to a script. In your case, you passed no parameters and the reported result is 0 .

Can you assign variables in bash?

A variable in bash is created by assigning a value to its reference. Although the built-in declare statement does not need to be used to explicitly declare a variable in bash, the command is often employed for more advanced variable management tasks.


1 Answers

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.

like image 135
Carl Norum Avatar answered Sep 29 '22 16:09

Carl Norum