The gzip command can be used to compress files. The tar command an be used to compress a directory.
In this example, the /home/john.doe directory contains a single file, example.txt. The example.txt file is not compressed, and is 672 bytes.
ll /home/john.doe -rw-r--r-- john.doe john.doe 672 Jan 01 :17:16 example.txt
The gzip command can be used to compress example.txt.
This will create a new file named example.txt.gz and remove the original example.txt file. In this example, the compressed file is 52 bytes.
ll /home/john.doe -rw-r--r-- john.doe john.doe 52 Jan 01 :17:16 example.txt.gz
Compress every file in a directory
The -r or --recursive option can be used to compress every file at or below a directory. This does not create one .gz file that contains every file in the directory. Instead, this creates individual .gz files for each file in the directory. If you want to create one file that contains every file in the directory, you would create a tar archive.
In this example, every file at and below /home/john.doe will be compressed.
gzip -r /home/john.doe
When manually issuing the gzip command, you may be prompted "do you want to overwrite". If you are using gzip in a script, you may want to set a default action, such as "y" to overwrite or "n" to not overwrite. In this example, the default action will be "n" to not overwrite.
yes n | gzip example.txt
The -1 through -9 options can be used to select the compression level. -1 will have the least compression, but will be the fastest to compress. -9 will have the most compression, but will be the slowest to compress. In this example, example.file is compressed with the most compression. If the compression level is not specified, the default compression level used is -6.
gzip -9 example.txt
The -l or --list option can be used to view statistics of a compressed gzip file. The -l option will display the size of the uncompressed file, the size of the compressed file, the compression percentage, and the name of the uncompressed file.
gzip -l /home/john.doe/example.txt.gz compressed uncompressed ratio uncompressed_name 52 672 96.9% example.txt
Or, to list the compression level of every file in a directory.
gzip -l /home/john.doe/*
The -d, --decompress, or --uncompress option can be used to uncompress a gzip compressed file. In this example, example.txt.gz is uncompressed. Similarly, the gunzip command can also be used to decompress a gzip compressed file.
gzip -d example.txt.gz