Linking files (ln command)

Linking files with the ln command is a convenient way to work with the same data as if it were in more than one place.

Links are created by giving alternate names to the original file. The use of links allows a large file, such as a database or mailing list, to be shared by several users without making copies of that file. Not only do links save disk space, but changes made to one file are automatically reflected in all the linked files.

The ln command links the file designated in the SourceFile parameter to the file designated by the TargetFile parameter or to the same file name in another directory specified by the TargetDirectory parameter. By default, the ln command creates hard links. To use the ln command to create symbolic links, add the -s flag.
Note: You cannot link files across file systems without using the -s flag.

If you are linking a file to a new name, you can list only one file. If you are linking to a directory, you can list more than one file.

The TargetFile parameter is optional. If you do not designate a target file, the ln command creates a file in your current directory. The new file inherits the name of the file designated in the SourceFile parameter.

See the following examples:
  • To create a link to a file named chap1, type the following:
    ln -f chap1 intro
    This links chap1 to the new name, intro. When the -f flag is used, the file name intro is created if it does not already exist. If intro does exist, the file is replaced by a link to chap1. Both the chap1 and intro file names refer to the same file.
  • To link a file named index to the same name in another directory named manual, type the following:
    ln index manual
    This links index to the new name, manual/index.
  • To link several files to names in another directory, type the following:
    ln chap2 jim/chap3 /home/manual
    This links chap2 to the new name /home/manual/chap2 and jim/chap3 to /home/manual/chap3.
  • To use the ln command with pattern-matching characters, type the following:
    ln manual/* .
    Note: You must type a space between the asterisk and the period.
    This links all files in the manual directory into the current directory, dot (.), giving them the same names they have in the manual directory.
  • To create a symbolic link, type the following:
    ln -s /tmp/toc toc
    This creates the symbolic link, toc, in the current directory. The toc file points to the /tmp/toc file. If the /tmp/toc file exists, the cat toc command lists its contents.
  • To achieve identical results without designating the TargetFile parameter, type the following:
    ln -s /tmp/toc