cp and mv if the file named already exists

17,530

Solution 1

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)

Solution 2

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:
17,530

Related videos on Youtube

user63626
Author by

user63626

Updated on September 18, 2022

Comments

  • user63626
    user63626 almost 2 years

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

    $ cp to_do done
    $ mv to_do done
    
    • devnull
      devnull over 10 years
      It's copied (in case of cp) and replaced (in case of mv)!
  • Graeme
    Graeme over 10 years
    cp and mv will refuse to replace a file with a directory. Also, you could mention the -i option.
  • Matteo
    Matteo over 10 years
    @Graeme The OP specifically asked about a file
  • Graeme
    Graeme over 10 years
    Yeah, the target file. But to_do could also be a directory, in which case cp/mv would not replace done.
  • James Hebden
    James Hebden over 10 years
    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
    James Hebden about 10 years
    @kojiro You're right of course.