5 UNIX / Linux Compress Command Examples for Files and Directory

Compress is one of the compression utilities available on Linux.

This command does the compression and reduces the file size using the Lempel-Ziv algorithm.

The compressed file extension that is created by this utility is .Z

Please note that compress command is part of ncompress package, which contains utilities for fast compression and decompression.

1. Basic usage

As shown below, by default this will compress the given file, and create an compressed output file by appending .Z extension to the input file.

# compress users.txt

# ls -l
-rw-r--r--. 1 ramesh dba   1987453 Jan  2 11:03 users.txt.Z

2. Verbose Option

If you like to know how much compression it has done, use the verbose option: -v

As shown below, this will explain exactly what the command is doing:

# compress -v users.txt
users.txt:  -- replaced with users.txt.Z Compression: 28.00%

3. Use Standard Output

Instead of creating the default output file with .Z extension, you can also redirect the compressed output to just the standard-out, which will just spit out some non-printable character as shown below.

# compress -c users.txt
r´)3
êÐñÍ/,HQL7/ÄJ
)¨@Ín&\1FË/yaeÇ!G¢QP
Ê8¢E=oI

-c option is helpful only when you combine it with > and write the output to a different file as shown below. In this case, instead of creating the output file as users.txt.Z, it created as newfile.Z

# compress -c users.txt > newfile.Z

# ls -l
-rw-r--r--. 1 ramesh dba   1987453 Jan  2 11:05 newfile.Z

4. Force Compression

When the file already exist, compress command will prompt user before overwriting as shown below.

# compress users.txt
users.txt.Z already exists.
Do you wish to overwrite users.txt.Z (y or n)? n
users.txt.Z not overwritten

However, the above is not very helpful, when you are using compress inside a shell script, and when you know, it is Ok to overwrite an existing file. In that case, you can use -f option to force the compress command to overwrite the output file without prompting user as shown below.

# compress -f users.txt

5. Recursive Compression

When you use -r flag, it will compress all the files in the given directory and sub-directories recursively.

It is helpful to combine the -r option with -v to see exactly what the command is doing as shown below.

# compress -rv project1
project1/less.sh:  -- replaced with project1/less.sh.Z Compression: 2.77%
project1/glib2.csh:  -- replaced with project1/glib2.csh.Z Compression: 10.41%
project1/lang.sh:  -- replaced with project1/lang.sh.Z Compression: 54.13%
project1/which2.sh:  -- replaced with project1/which2.sh.Z Compression: 8.28%

The following output shows that the files inside the given directory are compressed successfully.

# ls -l  project1
-rw-r--r--. 1 root root  172 May 12 11:36 glib2.csh.Z
-rw-r--r--. 1 root root 1241 May 12 11:36 lang.sh.Z
-rw-r--r--. 1 root root  105 May 12 11:36 less.sh.Z
-rw-r--r--. 1 root root  155 May 12 11:36 which2.sh.Z