atomic directory replacement

Jump to navigationJump to search

I don't know of any way to atomically replace one directory with another, but you can atomically replace one symlink with another using 'mv'. This can be used to simulate atomic directory replacement.

Note that operations that cross different filesystems may not be atomic. Operations that cross network filesystems are almost never atomic.

# Assume there is an existing symlink named "reports", which points
# to an old directory of reports.
ln -s /var/my_application/reports.old reports

# Now we create a directory of new reports that we want to become
# the target of the "reports" symlink.
mkdir /var/my_application/
echo "hello" > /var/my_application/

# Now we create a new symlink, which points to the new reports.
ln -s /var/my_application/ /var/my_application/reports.newlink

# Now we can replace the old symlink with the new symlink.
# This destroys the old symlink, but it is atomic.
# Don't forget the '-T' option on 'mv', otherwise reports.newlink would
# be moved inside of the directory that reports points to.
mv -T /var/my_application/reports.newlink /var/my_application/reports