File Management  «Prev  Next»

Lesson 6Creating a link to a file
ObjectiveCreate symbolic links using ln -s.

Creating Symbolic Links with ln -s

ln -s target_path link_name

The -s option requests a symbolic link, also called a soft link or symlink. The first operand is the target pathname that the link will store. The second is the name to create. In the basic form used here, the second operand must be an unused name, not an existing directory.

ln -s project/qa/test_plan.html qa.html

This command creates qa.html in the current directory and stores project/qa/test_plan.html as its target. It does not copy the test plan, rename it, or move it. Opening qa.html normally follows the link and opens the test plan.

Read the operands aloud as “target first, new link name second.” Reversing them is a common mistake. Also distinguish the shell prompt from the command: the screenshot below uses lab1% as its prompt. You type the command after that prompt, not the prompt itself.

Quote an operand if it contains spaces, for example ln -s "project/qa/test plan.html" "test plan link.html". The quotes group each pathname as one shell argument; they are not stored as part of the filename. Use straightforward learner-owned paths while practicing.

Build a Small Practice Directory

Start in a directory you own and choose a new name for this exercise. Run the following setup one command at a time. If mkdir link-practice reports that the name already exists or cannot be created, stop and choose an unused directory name before continuing. The later output redirection is intended to create a new practice document.

mkdir link-practice
cd link-practice
mkdir -p project/qa
printf '%s\n' 'Example test plan' > project/qa/test_plan.html

Confirm that changing into the new directory succeeded before running the remaining commands. The mkdir -p command creates the nested directories needed for the example. The printf command writes a small text file with a final newline. Despite its .html suffix, this practice file contains plain example text; no browser or web server is required.

ln -s project/qa/test_plan.html qa.html
ls -l qa.html
cat qa.html

The final command should display Example test plan. This checks more than the existence of the link: it demonstrates that the stored pathname resolves to a readable file. If creating the link reports an error, investigate before interpreting the later commands as a successful test.

The resulting layout is conceptually:

link-practice/
    qa.html -> project/qa/test_plan.html
    project/
        qa/
            test_plan.html

The arrow is explanatory notation. It is not part of the link name or a shell command. Both paths lead to the same document when the symlink is followed, so editing the document through the link does not create an independent draft.

A plain directory listing may not make file types obvious. Classification indicators and long listings provide more information:

ls -F
ls -l qa.html

With the ordinary classification behavior illustrated here, ls -F appends @ to a symbolic-link name and / to a directory name. Thus qa.html@ identifies the link. The at sign is added for display; use qa.html, without the at sign, when naming the link in a command.

A long listing of the link itself begins with the file-type character l. Near the end, it shows the link name, an arrow, and the stored target pathname. Do not confuse the lowercase letter l in ls -l with the digit one. Options that request dereferencing can change what is displayed, so use the commands shown while learning the distinction.

Read the Historical Command Example

Terminal example creates qa.html with ln -s, then shows its at-sign classification and stored project/qa/test_plan.html target.
The historical terminal shows a directory listing before and after creating qa.html, followed by a long listing that identifies the symbolic link and its target pathname.

The important commands and observations from the image are:

ln -s project/qa/test_plan.html qa.html
ls -F
ls -lF

The first listing shows the existing project directory. After ln -s, the classification listing includes qa.html@. The long listing then shows qa.html -> project/qa/test_plan.html. In the narrow terminal window, the target wraps onto the next display line; that wrapped line is not another command.

The screenshot is historical evidence, not a template for exact output on your computer. User and group names, dates, spacing, allocation totals, and directory sizes vary. Its size field shows 25, although the visible target pathname contains 24 ASCII characters. Treat that discrepancy as a limitation of the old example, not as a rule for calculating link sizes.

The window title identifies a Telnet session. The lesson concerns shell commands and does not require Telnet; use your local terminal or an appropriately configured SSH session. No remote connection is needed for the practice directory above.

The target project/qa/test_plan.html is relative because it does not begin with /. When the link is followed, that pathname is interpreted from the directory containing the symbolic link. It is not interpreted from whichever directory the reader happens to be working in.

This explains why the original example works: qa.html and project are entries in the same containing directory. If you access the link from somewhere else using a longer pathname, its relationship to project remains the same.

Now suppose you want the link inside a separate shortcuts directory. From the top of the same practice directory, use:

mkdir shortcuts
ln -s ../project/qa/test_plan.html shortcuts/qa.html
cat shortcuts/qa.html

Here .. moves from the containing shortcuts directory to its parent before entering project. Using project/qa/test_plan.html unchanged would instead look for a project directory inside shortcuts. The fact that you ran ln from the parent directory would not fix that stored path.

This is an important distinction: the shell uses the second operand to decide where to create the link, while the relative pathname stored in the first operand is later resolved from the link's containing directory. Check both locations separately when a newly created link cannot be opened.

Choose Relative or Absolute Targets Deliberately

An absolute target begins with / and is resolved from the root of the applicable filesystem namespace. For example, /home/alex/project/qa/test_plan.html identifies a full path in that namespace. It is an illustration, not a path you should assume exists on your machine.

An absolute target can be convenient when the link should refer to a known location regardless of where the link itself is placed. A relative target can be convenient when a directory tree and its links will move together while preserving their relationships. Neither form automatically follows every rename or relocation.

Before creating the link, ask where the target should be found from the link's eventual location. After creation, inspect the stored pathname and try the intended access. A successful ln -s operation alone does not establish that the target exists or is accessible.

Create a Link to a Directory

Symbolic links can also refer to directories. From the top of the practice directory, create a convenient name for its QA directory:

ln -s project/qa qa-dir
ls -l qa-dir
ls qa-dir/

The first listing inspects the link. The second uses a trailing slash to access the target directory and list its contents. You can also change into it with cd qa-dir. Shells may display logical paths containing the symlink name; that does not mean a second directory was created.

Creating a directory symlink is different from giving an existing directory as the final operand to ln. When the destination operand is an existing directory, the command normally creates a link inside it rather than replacing that directory with the requested link name. Keeping new link names unused makes the introductory examples unambiguous.

A symbolic link can store a target pathname that does not currently exist. Such a link is dangling when that pathname cannot be resolved. It might have been created intentionally before the target, or it might result from a spelling error, a mistaken relative path, or a later rename.

When access fails, inspect the link with ls -l, read its target text, and trace that path from the correct starting directory. Check capitalization and every directory component. On case-sensitive filesystems, QA and qa can name different entries.

Do not diagnose every failure as a missing file. Directory traversal and target permissions still apply, and a filesystem containing the target might not be mounted. The permissive-looking mode bits often displayed for a symlink do not grant permission to read its target. A link also does not mount storage or bypass an access restriction.

Renaming the target can break the stored pathname because the symlink text is not automatically rewritten. However, moving a whole directory tree can preserve a relative link if the relevant relationships remain intact. Describe the actual path change instead of assuming that every move breaks every link.

If the link name already exists, stop and inspect it. Do not add a force option simply to silence the error: the existing entry may be useful. Choose a fresh name for practice. For a link known to be disposable, removing that link and creating the intended one is easier to understand than introducing replacement options prematurely.

From the top of the practice directory, this command removes the practice link itself:

rm qa.html

Use the exact link name without a trailing slash. The target document at project/qa/test_plan.html remains. You can confirm that by reading the target directly. This example concerns removing the link entry; it does not imply that every utility avoids following symlinks during other operations.

Conversely, deleting or renaming the target can leave the link behind as a dangling entry. If another file later appears at the stored target pathname, the symbolic link can resolve to that new file. It refers through a name, not to an immutable identity or a saved version of the original contents.

Without -s, ln normally creates a hard link to an existing file. For example, with an existing regular file and an unused second name:

ln report.txt report-hard.txt

The two directory entries identify one file inode within one filesystem. Neither name is a privileged original. Removing one name leaves the other usable. Inodes contain metadata and information used to locate contents; they are not simply physical disk addresses.

Hard links cannot cross filesystem boundaries, and ordinary users generally cannot create hard links to directories. Symbolic links support both directory references and paths across mounted filesystems. These are differences in behavior, not evidence that one kind should always replace the other.

Modifying shared content in place through a hard-link name affects the shared file. Replacing one directory entry with a new file can separate that name from the inode referenced by the other names. Removing the final hard-link name can still leave storage allocated while a process holds an open reference. Keep these distinctions in mind without turning this practical symlink lesson into a filesystem internals reference.

Check Your Understanding

The reliable sequence is to choose the target path, create an unused link name, inspect the link, and verify access. In the next lesson, you will use find to search for files and directories.

Reference: GNU Coreutils documentation for ln.

SEMrush Software 6 SEMrush Banner 6