Tar overwrites read only files
Solution 1
Tar didn't overwrite the existing read-only file, it removed it and then created a new file with the same name. This is a consequence of the way -x works; it replaces existing versions of a file by design in order to accommodate the old incremental backup method of appending files to an existing archive. A tar archive might have multiple versions of a file in it; only the last one will appear on disk after extraction is completed. A side effect of this is that tar also removes existing copies of files even if they appear only once in the archive.
Solution 2
The fact that a file cannot be removed does not depend on a file's permissions being set to read-only, but on the permissions of the parent directory.
When you have write access to a directory, you can remove read-only files in that directory even if you do not own those files yourself (link).
# file removal test
(
mkdir -p test
echo hello > test/file.txt
chmod -w test
chmod -w test/file.txt
sudo chown root:wheel test/file.txt
#sudo chflags uchg test/file.txt
ls -ld test test/file.txt
rm -fv test/file.txt
echo
chmod 700 test # set write permission
ls -ld test test/file.txt
rm -fv test/file.txt
)
If you remove the write access to the test
directory in your example above, gnutar
(on Mac OS X) cannot remove test/1.txt
and complains:
# gnutar: ./test/1.txt: Cannot open: File exists
# gnutar: Exiting with failure status due to previous errors
# After
tartest() {
dirperms="$1"
mkdir -p test
[[ -f test/1.txt ]] && chmod +w test/1.txt
echo "Before" > test/1.txt
gnutar -czf ./test.tgz ./test
echo "After" > test/1.txt
chmod -w test/1.txt
chmod "${dirperms}" test
gnutar -xzf ./test.tgz
cat test/1.txt
return 0
}
tartest 755
tartest 555
Related videos on Youtube
Jakub
Updated on September 18, 2022Comments
-
Jakub almost 2 years
I created directory
test
, created file1.txt
intest
, wrote 'Before' in this file. Then I wentcd ..
and used the command:
tar -cvzf ./test.tgz ./test
Then I entered the test dir again. Opened the
1.txt
file again. Changed content to "After". I saved the file and changed chmod to read only by executing:chmod -w ./1.txt
So for now my
1.txt
is read only. Then I go upcd ..
and extract the
test.tgz
archive.tar -xvzf ./test.tgz
Then I go again to test dir, do
cat 1.txt
and get "Before".
It is not logical that this happens, since the file was set to be read-only. Why does it happen?
-
Jakub over 12 yearsThank you for your answer, Kyle Jones. So I will use --exclude option to exclude files I don't want to be overwritten.