3
I recently got bit by a misbehaving in a bash script of mine and was wondering:
- is this the expected system behavior, or is it a bug
- what are the ideal workarounds
Essentially, the problem boiled down to this. First I had an existing directory structure with the following layout.
/opt/dir/file.a
/opt/dir/file.b
/opt/dir/file
where file
is a hard link to file.a
. I wanted to replace file
with a shell script which selected file.a
or file.b
depending on parameters, so I ran something like this:
cp my_file /opt/dir/file
The problem is that since file
is a hard link to file.a
, (meaning that the two files are really just two names for the same inode), the change was reflected under both file
and file.a
. This was obviously not what what I wanted.
It seems that the cp
command effectively opened /opt/dir/file
with the truncate file flag something like: fopen("file", "w+")
. and wrote to it. I was expecting it to break the hard link since I was copying a new file to that name.
Is this the correct and expected behavior of cp
? It seems unintuitive to me. When I copy a file from one location to another, in my mind I am replacing it, not rewriting it. Is there a flag for cp
to avoid this? My current work-around is that I rm /opt/dir/file && cp my_file /opt/dir/file
.
Looking at the man page it appears that cp --remove-destination my_file /opt/dir/file
may be the correct solution, but I am still interested in what everyone has to say on the subject.
Actually it is very intuitively for me. It is the same file. You write to the same file. Both places get the updated content. But what is intuitive will vary per person and it is hard to give one clear, perfect answer. Just opinions. IMHO that makes it off-topic. – Hennes – 2013-09-11T00:18:38.073
@Hennes, thanks for your response. I would say that there is a difference between "hard to answer" and "off topic". Certainly the answer may be "primarily opinion based" but that's a different story. I would like to clarify the reason I found it unintuitive. I know that writing to one updates both, but, my mental image of a copy is to "replace" the destination, not "update" it. However, I do understand your point/ – Evan Teran – 2013-09-11T00:38:06.740
I think the question is both hard to answer, will have opinions, is interesting and is well written. For me three of those make it a good question on [Su].
Is there a flag for cp to avoid this?
makes it an actual answerable question. (which you self answered). – Hennes – 2013-09-11T00:42:50.667