Linux: Creating Soft Links as Directories

Optional test: create a soft-link for directory as hard-links are not allowed

source=/nfs-share/linux03/docker/containers
destinationdirectory=/var/lib/docker
sudo mkdir -p $source
sudo ln -sfn $source $destinationdirectory

# Expected result:
# The -sfn will force overwrite if link already exists to avoid this error
# ln: failed to create symbolic link '/var/lib/docker/containers': File exists
# -n, --no-deference: treat LINK_NAME as a normal file if it is a symbolic link to a directory

This is fail-safe sequence to create a symlink of an existing directory toward a destination. In this example, the directory is being held by a process named docker. Thus, it’s necessary to stop that process > delete its directory > recreate the directory as a link toward a desired destination

# The below sequence would pre-empt this error:
# ln: /var/lib/docker/containers: cannot overwrite directory
sudo su
systemctl stop docker
directoryname=containers
source=/nfs-share/linux03/docker/$directoryname
destinationdirectory=/var/lib/docker
sudo mkdir -p $source
sudo rmdir $destinationdirectory/directoryname
sudo ln -sfn $source $destinationdirectory
systemctl start docker

Optional: how to remove a symlink

directoryname=containers
destinationdirectory=/var/lib/docker
rm $destinationdirectory/$directoryname

Leave a Reply

Your email address will not be published. Required fields are marked *