How to Recursively Compress Directories Using gzip in Linux

When you are architecting a backup script on a Linux server and you must compress a massive, geometrically complex directory structure containing hundreds of subdirectories, executing a standard compression command against individual files is mathematically impossible. To force the Linux kernel to execute an algorithmic deep dive—penetrating every folder and compressing every single file in place—you must deploy the recursive vector within the gzip command.

Understanding the Recursive Architecture

Unlike tar (which groups files into a single archive block before compressing), the standard gzip command is designed to process individual files on a 1:1 ratio. By default, if you point gzip at a directory, the engine will algorithmically crash, refusing to process the directory node itself. However, by injecting the Recursive flag (-r), you mathematically override this behavior, forcing the engine to traverse the directory tree and compress every individual file it finds.

Executing the Recursive Compression Matrix

Imagine you have a massive directory named /var/log/apache2/legacy_logs/ containing dozens of subfolders, each filled with uncompressed text files. You want to compress every single file to save disk space, but you must preserve the exact directory geometry.

To execute the recursive vector, open your terminal and type:

gzip -r /var/log/apache2/legacy_logs/

The exact millisecond you press Enter, the gzip engine intercepts the directory node. It algorithmically crawls into the root folder, compressing every file. It then penetrates the first subdirectory, compresses every file there, and continues this geometric progression until it reaches the absolute bottom of the file tree.

Critical Geometric Reality: Every single text file will be violently converted into an independent .gz file (e.g., access.log becomes access.log.gz), and the original uncompressed files will be permanently deleted from the physical disk. The directory structure itself remains intact, but its contents are entirely compressed.

Executing Recursive Decompression

If you must reverse this algorithmic process and decompress the entire geometric structure simultaneously, you simply combine the decompress (-d) flag with the recursive (-r) flag.

gzip -dr /var/log/apache2/legacy_logs/

The engine will traverse the tree backward, ripping the .gz compression off every file it encounters.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.