Break all hardlinks within a folder

There is room for improvement in your script, for example adding a -p option to the cp command so that permissions and timestamps will be preserved across the unhardlink operation, and you could add some error handling so that the temp file is deleted in case of an error, but the basic idea of your solution is the only one that will work. To unhardlink a file you have to copy it and then move the copy back over the original name. There is no "less crude" solution, and this solution has race conditions in case another process is accessing the file at the same time.


If you want to burn up disk space, and you have a relatively modern version of tar (e.g., what's on Ubuntu 10.04 and CentOS 6), you can play with the --hard-dereference option.

Something like:

$ cd /path/to/directory
$ ls -l *
bar:
total 12
-rw-rw-r-- 2 cjc cjc 2 May  6 19:07 1
-rw-rw-r-- 2 cjc cjc 2 May  6 19:07 2
-rw-rw-r-- 1 cjc cjc 2 May  6 19:07 3

foo:
total 12
-rw-rw-r-- 2 cjc cjc 3 May  6 19:07 1
-rw-rw-r-- 2 cjc cjc 2 May  6 19:07 2
-rw-rw-r-- 1 cjc cjc 2 May  6 19:07 4

(where I had run ln foo/[12] bar)

$ tar cvf /tmp/dereferencing.tar --hard-dereference .
$ tar xvf /tmp/dereferencing.tar
$ ls -l *
bar:
total 12
-rw-rw-r-- 1 cjc cjc 2 May  6 19:07 1
-rw-rw-r-- 1 cjc cjc 2 May  6 19:07 2
-rw-rw-r-- 1 cjc cjc 2 May  6 19:07 3

foo:
total 12
-rw-rw-r-- 1 cjc cjc 3 May  6 19:07 1
-rw-rw-r-- 1 cjc cjc 2 May  6 19:07 2
-rw-rw-r-- 1 cjc cjc 2 May  6 19:07 4

From the man page:

   --hard-dereference
          follow hard links; archive and dump the files they refer to

Tags:

Unix

Hardlink