Vim Inode – Why Inode Doesn’t Change with Hard Link

hard linkinodelnvim

I use Vim 8.2 to edit my files in my Ubuntu 18.04. When I open a file, do some changes and quit with Vim, the inode number of this file will be changed.

As my understanding, it's because the backup mechanism of my Vim is enabled, so each edition will create a new file (.swp file) to replace the old one. A new file has a new inode number. That's it.

But I found something weird.

As you can see as below, after the first vim 11.cpp, the inode has changed, 409980 became 409978. However, after creating a hard link for the file 11.cpp, no matter how I modify the file 11.cpp with my Vim, its inode number won't change anymore. And if I delete the hard link xxx, its inode number will be changed by each edition of my Vim again.

This really makes me confused.

$ ll -i ./11.cpp
409980 -rw-rw-r-- 1 zyh zyh 504 Dec 22 17:23 ./11.cpp

$ vim 11.cpp     # append a string "abc" to the file 11.cpp
$ ll -i ./11.cpp
409978 -rw-rw-r-- 1 zyh zyh 508 Dec 22 17:25 ./11.cpp

$ vim ./11.cpp   # remove the appended "abc"
$ ll -i ./11.cpp
409980 -rw-rw-r-- 1 zyh zyh 504 Dec 22 17:26 ./11.cpp

$ ln ./11.cpp ./xxx   # create a hard link
$ ll -i ./11.cpp
409980 -rw-rw-r-- 2 zyh zyh 504 Dec 22 17:26 ./11.cpp

$ vim 11.cpp     # append a string "abc" to the file 11.cpp
$ ll -i ./11.cpp
409980 -rw-rw-r-- 2 zyh zyh 508 Dec 22 17:26 ./11.cpp

$ vim 11.cpp     # remove the appended "abc"
$ ll -i ./11.cpp
409980 -rw-rw-r-- 2 zyh zyh 504 Dec 22 17:26 ./11.cpp

Best Answer

It seems the setting backupcopy is auto (run :set backupcopy? in Vim to confirm).

The main values are:

yes make a copy of the file and overwrite the original one
no rename the file and write a new one
auto one of the previous, what works best

[…]

The auto value is the middle way: When Vim sees that renaming file is possible without side effects (the attributes can be passed on and the file is not a link) that is used. When problems are expected, a copy will be made.

In case it's not clear: yes (copy and overwrite) does not change the inode number, no (rename and write anew) does change it.

In your case at first auto was like no. After ln ./11.cpp ./xxx Vim noticed there is another link and auto worked like yes.

Related Question