Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Symlinking to Directories in Linux


Linux
David Egan

If you need to symlink a directory in Linux, you need to make a distinction. The linked-to directory is intended to:

  • Be the symlink: navigating to the symlink is equivalent to navigating to the linked directory
  • Be accessed via a link within the linking directory

If you intend the former, you need to be careful that the directory does not already exist - if it does, the symlink will be placed inside the existing directory.

In this case, the ‘directory’ path/to/current will contain the files from /path/to/target. Crucially, /path/to/current does not exist.

# /path/to/current does not exist
ln -s /path/to/target path/to/current

# cd to the parent directory and list contents...
cd path/to && ls -la
# Output:
drwxrwxr-x 2 david david 4096 Oct 18 21:01 ./
drwxrwxr-x 8 david david 4096 Oct 18 21:01 ../
lrwxrwxrwx 1 david david    4 Oct 18 21:01 current -> /path/to/target/

In this case, to access files in /path/to/target via the symlink you would reference /path/to/current:

cd path/to/current && ls -la
# Output:
drwxrwxr-x 2 david david 4096 Oct 18 21:03 ./
drwxrwxr-x 7 david david 4096 Oct 18 21:09 ../
-rw-rw-r-- 1 david david    0 Oct 18 21:02 file-1
-rw-rw-r-- 1 david david    0 Oct 18 21:02 file-2
# Where file-1 and file-2 are contained in /path/to/target

In this case, the /path/to/current directory does exist:

# /path/to/current does exist
ln -s /path/to/target path/to/current

cd path/to/current && ls
# Output:
drwxrwxr-x 2 david david 4096 Oct 18 21:01 ./
drwxrwxr-x 8 david david 4096 Oct 18 21:01 ../
lrwxrwxrwx 1 david david    4 Oct 18 21:01 target -> /path/to/target

In this case, to access files in /path/to/target via the symlink you would reference /path/to/current/target.

If you’re using the --link-dest option with rsync to make incremental backups, make sure you are referencing the correct symlinked reference directory - if not, rsync won’t create hardlinks and your backups will not be incremental. I recently made this error when mis-referencing the most recent backup by dynamically adding a symlink to an already existing directory.

Resources


comments powered by Disqus