Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

What happens when you give the following commands if the file named done already exists?

$ cp to_do done
$ mv to_do done
share|improve this question
    
It's copied (in case of cp) and replaced (in case of mv)! –  devnull Mar 26 at 11:19
add comment

2 Answers 2

done will be replaced by the content of to_do

You can check with a simple test:

$ echo a > done
$ echo b > to_do
$ cp to_do done 
$ cat done
b

and

$ echo a > done
$ echo b > to_do
$ mv to_do done
$ cat done
b

Edit

Following the comments some additional info

  • done will not be replaced if either done or to_do are directories. If done is a directory the file to_do will be moved/copied in the directory. If to_do is a directory you will get an error message
  • using the -i option you can instruct mv and cp to warn when overwriting a file
  • on some distributions cp and mv are an alias to cp -i and mv -i (especially for the root user)
share|improve this answer
1  
cp and mv will refuse to replace a file with a directory. Also, you could mention the -i option. –  Graeme Mar 26 at 11:56
    
@Graeme The OP specifically asked about a file –  Matteo Mar 26 at 11:58
1  
Yeah, the target file. But to_do could also be a directory, in which case cp/mv would not replace done. –  Graeme Mar 26 at 12:02
    
It's worth noting that some distributions of Linux imply the -i option by default, so on some distributions you would be prompted whether or not you want to replace the destination file. –  James Hebden Mar 26 at 12:18
3  
@JamesHebden I don't think the word imply is quite the correct…implication. They may alias the -i option by default. –  kojiro Mar 26 at 12:29
show 1 more comment

Assuming that we're talking of regular files here, in the case of:

cp to_do done

If done is not writeable, you'll get an error message. Otherwise, the content of to_do will be copied over done. What that means is that done keeps the same inode, permissions, ownership, birth time. The -p (or -a in some implementations) would try and copy some of the attributes of to_do.

With:

cp -f to_do done

If you don't have write access to done, cp will first unlink done (which you'll be able to do as long as you've got write access to the current directory and the current directory doesn't have the t bit set) and create a new one. cp will try and copy as many of the attributes of to_do, like it would if done didn't exist beforehand.

With

mv to_do done

to_do is just renamed. It's only the current directory that is modified. If done existed before hand, it will be unlinked first.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.