Every now and then we need to create symbolic links, or symlinks for the intimate. This way we can have a link, or pointer, to another file: the link looks like a regular file (or directory) but refers to a file (or directory) in another place (assuming the link is not broken, of course).

We usually open the terminal and ln -s foo bar around to create these links. This command creates a symbolic link (hence the -s flag) named bar that points to the file foo. Or is it the other way around: a link named foo pointing to bar? Damn it. I’ve done this a million times, what’s the order again?

Every time I create a symlink I need to stop for a moment and remember the mantra: ln <target> <link-name>. And then I get it wrong 42.137% of the times, approximately. Yeah, I have the manual right in front of me, some ~100 columns to the side. But still, I flip the arguments… my brain is weird, what can I do?

Well, I can open a Python interpreter.

Python has an amazing module to work with filesystem paths called Pathlib, since Python 3.4. This module allows you to create Path objects and with a Path object you can do file operations like: create/delete a file/directory, check if it is a directory/block device/socket, list contents of a path, change file permissions like chmod, and many other really cool stuff.

Among those other really cool stuff is: create a Path and turn it into a real symbolic link! Like this:

from pathlib import Path

Path("/tmp/my_link_to_fstab").symlink_to("/etc/fstab")

And voilà! Mind blowing, isn’t it? We now have a new symbolic link at /tmp/my_link_to_fstab that points to /etc/fstab:

$ file /tmp/my_link_to_fstab
/tmp/my_link_to_fstab: symbolic link to /etc/fstab

This is way easier to remember: create a Path representing where you want the link to exist and then write where to point it to. There’s no need anymore to think about the order of ln arguments.

Python is nice, use it. 🐍