os.Rename and hard link overwrite

I’ve run into unexpected behavior with the os.Rename() function with regards to hard links (on Linux.) If I have two files ‘a’ and ‘b’ that are hard links to the same file and try to rename one to the other, the operation fails and the return error is <nil>. The same operation from the bash shell results in a diagnostic:
mv: 'a' and 'b' are the same file
I thought that os.Rename() would return some kind of error code if the operation could not be completed.
The project https://github.com/HankB/go_rename demonstrates exactly what I am doing.

Is this a bug or a feature? Is there a way to determine that the operation failed other than to check if the files are the same beforehand or exploring to see if the overwritten file remains after the operation?

Thanks!

It looks like os.Rename is mostly just a wrapper around the rename(2) system call, which I guess returns no error in this case. The mv command probably does extra checks, and it seems you should too if you need to handle this situation. os.SameFile might help.

1 Like

Yes - thanks. That’s exactly the situation. I have coded that in C and the rename() call fails silently when the two files are links to the same file.

I have already employed the os.SameFile() to identify this situation rather than rely on the return status of os.Rename().

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.