How to add/update a file to an existing tar.gz archive?

To pull your file from your archive, you can use tar xzf archive.tar.gz my/path/to/file.txt. Note that the directories in the file's path will be created as well. Use tar t (i.e. tar tzf archive.tar.gz) to list the files in the archive.

tar does not support "in-place" updating of files. However, you can add files to the end of an archive, even if they have the same path as a file already in the archive. In that case, both copies of the file will be in the archive, and the file added later will override the earlier one. The command to use for this is tar r (or tar u to only add files that are newer than the archive) is the command to use. The . in the path should not be a problem.

There is a catch, though: you can't add to a compressed archive. So you would have to do:

gunzip archive.tar.gz
tar rf archive.tar data/data/com.myapp.backup/./files/settings.txt
gzip archive.tar

Which is probably not what you want to hear, since it means rewriting the entire archive twice over. If it's not a very large archive, it might be better to untar the whole thing and then re-tar it after editing. Alternately, you could use an uncompressed archive.


The tar file format is just a series of files concatenated together with a few headers. It's not a very complicated job to rip it apart, put your contents in, and put it back together. That being said, Jander described how tar as a program does not have the utility functions to do this and there are additional complications with compression, which has to both before and after making a change.

There are, however, tools for the job! There are at least two system out there which will allow you to to do a loopback mount of a compressed tar archive onto a folder, then make your changes in the file system. When you are done, unmount the folder and your compressed archive is ready to roll.

The one first option would be the archivemount project for FUSE. Here is a tutorial on that. Your system probably already has FUSE and if it doesn't your distribution should have an option for it.

The other option is tarfs. It's simpler to use, but I've heard it has some trouble with corrupting bzip2 archives so you might test that pretty thoroughly first.


Tar was originally meant to be used for tapes, so "replacing" files is not really in the design. However, you can use --delete to delete the file from the original tar and then -u to update the tar and re-add the file. It may take a bit, as tar needs to reorganize the archive internally.

Tags:

Archive

Tar

Gzip