cp and mv if the file named already exists
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 eitherdone
orto_do
are directories. Ifdone
is a directory the fileto_do
will be moved/copied in the directory. Ifto_do
is a directory you will get an error message- using the
-i
option you can instructmv
andcp
to warn when overwriting a file - on some distributions
cp
andmv
are an alias tocp -i
andmv -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.
Related videos on Youtube
user63626
Updated on September 18, 2022Comments
-
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 over 10 yearsIt's copied (in case of
cp
) and replaced (in case ofmv
)!
-
-
Graeme over 10 years
cp
andmv
will refuse to replace a file with a directory. Also, you could mention the-i
option. -
Matteo over 10 years@Graeme The OP specifically asked about a file
-
Graeme over 10 yearsYeah, the target file. But
to_do
could also be a directory, in which casecp
/mv
would not replacedone
. -
James Hebden over 10 yearsIt'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 about 10 years@kojiro You're right of course.