Great question! Let's break down how rsync handles write-protected files.
The key is understanding Unix/Linux filesystem permissions and directory operations. There are two important concepts here:
- Directory Permissions vs File Permissions
- The
unlink and link Operations
Directory Permissions
To modify (delete, create, rename) files in a directory, you need:
w (write) permission on the directory itself
x (execute) permission on the directory
You do NOT need write permission on the file itself to delete or rename it!
Here's why:
# Example directory structure
/snapshots/username/latest/ (drwxr-xr-x) # Directory has write permission
└── document.txt (-r--r--r--) # File is read-only
Even though document.txt is read-only, rsync can still:
- Create new files in
latest/ (directory is writable)
- Delete/rename files in
latest/ (directory is writable)
The Process Step-by-Step
When rsync updates a read-only file, it:
- Creates a temporary file (e.g.,
.document.txt.XXXXXX) with the new content
- Sets the desired permissions on the temporary file
- Uses the
rename() system call to atomically replace the old file
# What happens under the hood
$ ls -l latest/
-r--r--r-- document.txt # Original read-only file
# rsync creates temp file
-rw-r--r-- .document.txt.XXXXXX # Temporary file (writable)
# rsync sets permissions on temp file
-r--r--r-- .document.txt.XXXXXX # Now read-only
# rename() replaces old file
-r--r--r-- document.txt # New file in place
Proof with a Simple Test
You can demonstrate this yourself:
# Create a test directory
mkdir test
cd test
# Create a read-only file
echo "old content" > file.txt
chmod a-w file.txt
# Try to modify it directly - this fails
echo "new content" > file.txt
# Result: Permission denied
# But rsync can replace it!
echo "new content" > newfile
rsync -a newfile file.txt
cat file.txt
# Result: new content
The Relevant Options in Your Script
In your backup script:
OPTS="-rltgoi --delay-updates --delete --chmod=a-w"
--chmod=a-w makes the destination files read-only
- But
rsync still has write permission to the latest directory itself
And later:
chmod u-w $SNAP/$DATETAG
This removes write permission from the snapshot directory, but the files were already read-only from the --chmod=a-w option.
Why This is Safe
This approach is actually safer than allowing write permissions because:
- Files can't be accidentally modified in place
- Changes must go through the atomic
rsync process
- The hard-linked snapshots are protected from modification
- The atomic nature of
rename() means files are never left in a partially-updated state
The combination of directory permissions and atomic operations allows rsync to safely update read-only files while maintaining the integrity of your backup system.