How to Pipe Command Output to Compressed File in Ubuntu
This article demonstrates the method for redirecting command output directly into a compressed file within the Ubuntu terminal. Instead of saving large text logs and compressing them later, you can stream data through compression tools like gzip in real-time. This approach saves disk space and reduces input/output operations during execution.
To achieve this, you combine the pipe operator with the compression utility. The pipe operator sends the standard output of the first command to the standard input of the second command. In this case, the second command is the compression tool.
The basic syntax using gzip is:
your-command | gzip > filename.gz
For example, to save the output of the dmesg command directly into a compressed log, run:
dmesg | gzip > dmesg.log.gz
This creates a file named dmesg.log.gz containing the compressed data. You do not need to create an uncompressed version first.
To view the contents of this file without decompressing it permanently, use the zcat command:
zcat filename.gz
If you prefer higher compression ratios, you can substitute gzip with bzip2 or xz. The logic remains the same:
your-command | bzip2 > filename.bz2
your-command | xz > filename.xz
This method is ideal for logging scripts or backing up text-based data where storage efficiency is a priority.