Unix Power ToolsUnix Power ToolsSearch this book

10.5. Creating and Removing Links

The ln command creates both hard and soft (symbolic) links (Section 10.4). If by some strange chance you're using Minix or some other Unix that doesn't have symlinks, then ln won't have the -s option.

% ln filename linkname               . . . To create a hard link
% ln -s filename linkname           . . . To create a symbolic link

If creating a hard link, filename must already exist, or you will get an error message. On many versions of ln, linkname must not exist -- if it does, you will also get an error. On other versions, linkname may already exist; if you are allowed to write the file, ln destroys its old contents and creates your link. If you don't have write access for linkname, ln asks whether it is okay to override the file's protection. For example:

% ln foo bar
ln: override protection 444 for bar? y

Typing y gives ln permission to destroy the file bar and create the link. Note that this will still fail if you don't have write access to the directory.

You are allowed to omit the linkname argument from the ln command. In this case, ln takes the last component of filename (i.e., everything after the last slash) and uses it for linkname. Of course, this assumes that filename doesn't refer to the current directory. If it does, the command fails because the link already exists. For example, the following commands are the same:

.. Section 1.16

% ln -s ../archive/file.c file.c
% ln -s ../archive/file.c

Both create a link from file.c in the current directory to ../archive/file.c. ln also lets you create a group of links with one command, provided that all of the links are in the same directory. Here's how:

% ln file1 file2 file3 ... filen directory

This command uses the filename from each pathname (after the last slash) as each link's name. It then creates all the links within the given directory. For example, the first of the following commands is equivalent to the next two:

. Section 1.16

% ln ../s/f1 ../s/f2 current
% ln ../s/f1 current/f1
% ln ../s/f2 current/f2

You can replace this list of files with a wildcard expression (Section 33.2), as in:

% ln -s ../newversion/*.[ch] 

Note that symbolic links can get out-of-date (Section 10.6). Hard links can also be "broken" in some situations. For example, a text editor might rename the link textfile to textfile.bak then create a new textfile during editing. Previous links to textfile will now give you textfile.bak. To track down this problem, find the links (Section 9.24) to each file.

To remove a link, either hard or symbolic, use the rm command.

-- ML

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.