How can I create a hard link to a directory in Mac OS X?
This feature has been added to their file system in Mac OS X v10.5 (Leopard) (for time machine), but I could not find any information on actually using it from the command line.
While useful, there are some limitations to what hard links can do. For starters, they can only be created for regular files (not directories or special files). Also, a hard link cannot span multiple filesystems. They only work when the new hard link exists on the same filesystem as the original.
Press Command+Space, type “Terminal”, and then press “Enter” to open Terminal from Spotlight search. Navigate to Finder > Applications > Utilities > Terminal to launch the Terminal shortcut. The -s here tells the ln command to create a symbolic link. If you want to create a hard link, you'd omit the -s .
1 Answer. Every directory has a link to itself and its parent (that's why . of an empty directory will have a link count of 2). But because every directory links to its parent, any directory that has a subdirectory will have a link from that child.
The reason hard-linking directories is not allowed is a little technical. Essentially, they break the file-system structure. You should generally not use hard links anyway. Symbolic links allow most of the same functionality without causing problems (e.g ln -s target link ).
I have bundled up the suggested answer in a Git repository if anybody is interested: https://github.com/selkhateeb/hardlink
Once installed, create a hard link with:
hln source destination
I also noticed that unlink
command does not work on Mac OS X v10.6 (Snow Leopard), so I added an option to unlink:
hln -u destination
To install Hardlink, use Homebrew and run:
brew install hardlink-osx
Unfortunately Apple has crippled the ln
command. You can use the following program to create a hard link to a directory:
#include <unistd.h> #include <stdio.h> int main(int argc, char* argv[]) { if (argc != 3) { fprintf(stderr,"Use: hlink <src_dir> <target_dir>\n"); return 1; } int ret = link(argv[1],argv[2]); if (ret != 0) perror("link"); return ret; }
Take into account that the hard linked directories may not be in the same parent directory, so you can do this:
$ gcc hlink.c -o hlink $ mkdir child1 $ mkdir parent $ ./hlink child1 parent/clone2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With