5

I have a file which I want to copy from one directory to another directory.

Suppose that's the file some.txt to copy from folder1 to folder2

cp -r some.txt /folder2

I am able to copy this file but if the filename start with $ like $somefile.class then I am not able to copy the file, just getting file not exist error

cp -r $somefile.class /folder2
user2428118
  • 386
  • 7
  • 19

4 Answers4

16

First of all, you don't need the -r flag which is (from man cp):

-R, -r, --recursive
        copy directories recursively

That is only useful when copying entire directories and their contents. Then, whenever your file names contain strange characters, you need to either escape them or protect them with single quotes as the other answers have already suggested:

cp '$somefile.class' /folder2
cp \$somefile.class /folder2

Alternatively, you can use the shell's glob expansion feature to copy the file:

cp ?somefile.class /folder2
cp *somefile.class /folder2

The ? matches "any single character" and * matches "0 or more characters". So, using these globs will allow you to copy the target file without worrying about the name. However, bear in mind that you should use this carefully and make sure that the globs only match the file you want to copy. For example, the ones I used would also match Lsomefile.class.

user2428118
  • 386
  • 7
  • 19
terdon
  • 54,564
9

The $ character is used to signify a shell variable. If you file really starts with $ you should use single-quotes to prevent the shell from attempting to evaluate it as a variable:

cp -r '$somefile.class' /folder2
terdon
  • 54,564
Mureinik
  • 4,152
9

You need to escape any special character with backslash \

cp -r \$somefile.class /folder2

Read more about escaping here:

What characters do I need to escape when using sed in a sh script?

phuclv
  • 30,396
  • 15
  • 136
  • 260
0

None of these solutions worked for me in the case that the special character - was in front. The only thing that worked for me in that case was placing the current directory in front like this:

cp -r './-somefile.class' /folder2

Although it is not the $ sign, it's a special character and it might help some other people out there. The other solutions did not work such as putting \ before or placing single or double emphasis around the filename.

Joop
  • 109