Learn Bash - Hard and Symbolic Links

Question Click to View Answer

Create the directory ~/Desktop/lnk/ and add the file meat to the directory.

mkdir ~/Desktop/lnk/
cd ~/Desktop/lnk/
touch meat

Create a hard link called meat-link to the ~/Desktop/lnk/meat file.

ln meat meat-link

meat and meat-link have separate file names, but they point to the same text file.

Append the text "I like chicken" to the meat-link file and observe that this text is added to the meat file too.

echo "I like chicken" >> meat-link
cat meat # returns "I like chicken"

meat and meat-link point to the same text file, so when meat-link is used to update the text file, the same changes will be reflected in the meat file (because they're pointing to the same file).

Append the text "Peck me" to the meat file and observe that this text is appended to the meat-link file too.

echo "Peck me" >> meat
cat meat-link

meat and meat-link have different file names but point to the same underlying text file, so changes to the text file will be reflected when both file names are referenced.

Delete the meat file and verify that the text is still readable in the meat-link file.

rm meat
cat meat-link

The meat-link file still has the same contents and is not impacted when the meat file is deleted.

Create a hard link called desktop-link to the ~/Desktop directory.

You are not allowed to make hard links to directories. The following code will result in an error:

ln ~/Desktop desktop-link

Create the file martha and the symbolic link martha-link to the file.

touch martha
ln -s martha martha-link

View a long listing of all files in the directory and explain how this view demonstrates the symbolic link.

ls -lF

The long listing of files shows the following text: martha-link@ -> martha.

martha-link is a symbolic link that 'points to' to the martha file.

Append the text 'brady bunch' to the martha file and then view the contents of the file with martha-link.

echo 'brady bunch' >> martha
cat martha-link

Append the text 'weird show' to the martha-link file and then view the contents of the file with martha.

echo 'weird show' >> martha-link
cat martha

Delete the martha file and view the contents of the martha-link file.

When the martha file is deleted, the martha-link symbolic link points to a file that no longer exists and cannot be used. At this point, the symbolic link is considered to be broken.

rm martha
cat martha-link # errors out