Commands.page Logo

How to Append Files to Compressed Tar Archive in Ubuntu

This article outlines the process for adding new files to an existing compressed tar archive on Ubuntu Linux. Because standard compression formats do not support direct modification, you must follow a specific sequence of decompression, updating, and recompression. The following steps ensure your data remains intact while successfully integrating new content into your archive.

Understanding the Limitation

The tar command allows you to append files to an uncompressed archive using the --append or -r flag. However, this function does not work directly on compressed archives like .tar.gz or .tar.bz2. Attempting to run append commands on a compressed file will result in an error. To modify the archive, you must temporarily convert it back to an uncompressed tar file.

Step 1: Decompress the Archive

First, you need to remove the compression layer without extracting the individual files inside. Use the gunzip command to convert the .tar.gz file into a .tar file.

gunzip archive.tar.gz

This command creates a file named archive.tar in the same directory. If you are using a different compression format like bzip2, use bunzip2 instead.

Step 2: Append the New Files

Once the archive is uncompressed, you can use the tar command with the -r option to append your new files. Replace newfile.txt with the path to the file or directory you wish to add.

tar -rvf archive.tar newfile.txt

The -r flag tells tar to append files to the end of the archive, -v enables verbose output so you can see the process, and -f specifies the filename.

Step 3: Recompress the Archive

After successfully appending the new data, you must compress the archive back to its original format. Use the gzip command to compress the updated tar file.

gzip archive.tar

This restores the file to archive.tar.gz. Your archive now contains the original contents plus the newly added files.

Alternative Method: Recreate the Archive

For large archives, decompressing and recompressing can be time-consuming. An alternative approach is to extract the existing archive, add the new files to the folder, and create a new compressed archive from scratch.

tar -xzvf archive.tar.gz
cp newfile.txt archive_folder/
tar -czvf archive.tar.gz archive_folder/

This method ensures a clean archive structure but requires more disk space temporarily during the extraction process. Choose the method that best fits your storage and performance needs.