def things_n_stuff

Adventures in Code

Symbolic Links, Unix

There’s 2 types: soft links and hard links.

What they are:

Soft links tell the system to open the target of the link, ie the thing for which you’re creating a link. It’s just a reference to the original file. It’s a bit like how an alias operates in a GUI, and points the system to the right location to use the original.

Hard links point directly to a physical piece of data, to the file itself. (Whereas the soft link is a reference to the name of the file, the hard link is another name for the data itself.) Methinks that by the time you’ll be needing to make hard links you’ll probably know what, why, and how. So I’ll just talk about soft sym links.

How:

The syntax is: ln -s [file] [symlink_name], where both quantities are file names or full paths plus file name.

Demo:

Making a file and a link to it:

1
2
3
4
5
6
7
8
9
10
> echo 'puts "hi from the linked file"' > target_of_link.rb
> ruby target_of_link.rb
#=> puts "hi from the linked file"

> ls target*
#=> target_of_link.rb

> ln -s target_of_link.rb link_pointing_to_the_target_file.rb
> ls *target*
#=> link_pointing_to_the_target_file.rb target_of_link.rb

Afterwards, anything called on that link will act as if called on the original, as if the link didn’t even exist

1
2
3
4
5
6
7

> ruby link_pointing_to_the_target_file.rb 
#=> hi from the linked file

> less link_pointing_to_the_target_file.rb 
#=> puts "hi from the linked file"
  link_pointing_to_the_target_file.rb (END)

Removing the sym link:

Done the same as for any other file. And rest assured, removing the symbolic link doesn’t remove the target of that link.

1
2
3
> rm link_pointing_to_the_target_file.rb 
> ls *target*
#=> target_of_link.rb
Naming:

As far as I know the name of the link doesn’t matter at all, but it’s a good idea to name it similarly to or with the same extension as the original, so future devs know how to call the file.

Moved files:

The soft symbolic link, unlike Mac OSX GUI aliases, doesn’t follow the target file if it’s moved.

Let’s start over. Make the file and sym link:

1
2
3
4
> echo 'puts "hi from the linked file"' > target_of_link.rb
> ln -s target_of_link.rb link_pointing_to_the_target_file.rb
> ls *target*
#=> link_pointing_to_the_target_file.rb target_of_link.rb

Move the target:

1
2
> mkdir new_and_exotic_location/
> mv target_of_link.rb new_and_exotic_location/

Yup, it’s there:

1
2
3
4
> ls *target*
#=> link_pointing_to_the_target_file.rb
> ls new_and_exotic_location/*target*
#=> new_and_exotic_location/target_of_link.rb

But try to execute the sym link, and the system doesn’t know what’s being referenced:

1
2
> ruby link_pointing_to_the_target_file.rb 
#=> ruby: No such file or directory -- link_pointing_to_the_target_file.rb     (LoadError)

Righto. Over and out.