2

How do you create a hardlink (as opposed to a symlink or a Mac OS alias) in OS X that points to a directory? There is the command "ln target destination" but that only works when the target is a file.

I know that Mac OS, unlike other Unix environments, does allow hardlinking to folders (this is used for Time Machine, for example) but I don't know how to do it myself. I am also aware that using directory hardlinks is not "best practice" as it can cause some programs to recurse infinitely while scanning a tree.

username
  • 4,755
  • 19
  • 55
  • 78

4 Answers4

1

I heard it was intentionally disabled, since it can get complicated when you change the hard links to . and stuff.

Amandasaurus
  • 31,471
  • 65
  • 192
  • 253
1

Here is the link to the question on Stack Overflow:

What is the Bash command to create a hardlink to a directory in OS X?

splattne
  • 28,508
  • 20
  • 98
  • 148
1

It's supposed to be impossible.

From man 2 link:

int link(const char *path1, const char *path2);

 ....

In order for the system call to succeed, path1 must exist and both path1 and path2 must be in the same file system. As mandated by POSIX.1, path1 may not be a directory.

I tried the code in the other answer on MacOS X 10.5.6 - it didn't work when trying to create a link from a directory to the same name in the same directory.

However it does work if the two resulting directories don't have the same parent. It's necessary to read the linked article to find that out.

Alnitak
  • 21,191
  • 3
  • 52
  • 82
  • 1
    Apple specifically extended their link syscall to allow this behavior in limited circumstances to allow TimeMachine backups to consume less space, which still being logically complete – Dave Cheney May 09 '09 at 14:25
  • but haven't updated the man page to say so ;-) – Alnitak May 09 '09 at 14:50
  • 4
    The Open Group page (http://www.opengroup.org/onlinepubs/009695399/utilities/ln.html) for ln says, "If the -s option is not specified, whether a directory can be linked is implementation-defined." And my link page (on Ubuntu) doesn't say that (although this obviously doesn't work on Ubuntu). – Matthew Flaschen May 09 '09 at 19:21
0

You can't do it directly in BASH then. However... I found an article here that discusses how to do it indirectly: http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html by compiling a simple little program:

#include <unistd.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
   if (argc != 3)
      return 1;
   int ret = link(argv[1], argv[2]);
   if (ret != 0)
      perror("link");
   return ret;
}

$ gcc -o hlink hlink.c -Wall
username
  • 4,755
  • 19
  • 55
  • 78