gzip Command ExamplesThe gzip command in Linux compresses files, creating .gz files to save disk space. Below are 10 examples demonstrating various uses of the gzip command with detailed explanations.
gzip file.txt
Compresses file.txt, replacing it with file.txt.gz. The original file is removed.
Sample Output: No output unless an error occurs. The file file.txt.gz appears in the directory.
gzip -k file.txt
Compresses file.txt to file.txt.gz while keeping the original file.txt intact.
Sample Output: Both file.txt and file.txt.gz are present in the directory.
gzip -c file.txt > compressed_file.txt.gz
Compresses file.txt and writes the output to compressed_file.txt.gz without deleting the original file. The -c option outputs to stdout, and redirection saves it.
Sample Output: The compressed file compressed_file.txt.gz is created.
gzip *.txt
Compresses all .txt files in the current directory, creating corresponding .txt.gz files and removing the originals.
Sample Output: Files like file1.txt.gz, file2.txt.gz, etc., replace the original .txt files.
gzip -f file.txt
Forces compression, overwriting file.txt.gz if it already exists without prompting.
Sample Output: The existing file.txt.gz is overwritten with the new compressed version.
gzip -9 file.txt
Compresses file.txt using the maximum compression level (9) for the smallest file size, though it takes longer. Levels range from 1 (fastest, least compression) to 9 (slowest, most compression).
Sample Output: Creates file.txt.gz with maximum compression.
gzip -v file.txt
Compresses file.txt and displays verbose output, including the percentage of compression achieved.
Sample Output:
file.txt: 64.3% -- replaced with file.txt.gz
gzip -r /path/to/directory
Recursively compresses all files in the specified directory and its subdirectories, creating .gz versions and removing the originals.
Sample Output: No output unless errors occur. All files in the directory tree are compressed to .gz.
gzip -1 file.txt
Compresses file.txt using the minimum compression level (1) for faster processing but larger file size.
Sample Output: Creates file.txt.gz with minimal compression.
tar -cvf - files/ | gzip > archive.tar.gz
Creates a tar archive of the files/ directory and compresses it with gzip, saving the result as archive.tar.gz. The tar -cvf - outputs to stdout, which is piped to gzip.
Sample Output: Lists the files being archived, e.g.:
files/file1.txt
files/file2.txt
files/subdir/file3.txt
The compressed archive.tar.gz is created.
Note: The gzip command compresses individual files, not directories directly. For archiving and compressing directories, combine with tar (e.g., tar -czf archive.tar.gz files/). Check the man page (man gzip) for additional options and details specific to your system.