atomic directory replacement

From Noah.org
Revision as of 12:59, 29 May 2013 by Root (Talk | contribs) (Created page with 'Category:Engineering 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 b…')

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, 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 are usually not atomic, so beware.

# 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/reports.new
echo "hello" > /var/my_application/reports.new/report.txt

# Now we create a new symlink, which points to the new reports.
ln -s /var/my_application/reports.new /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