How to gzip all or specific files in Linux

The gzip (GNU zip) utility is older and less efficient than bzip2. Its flags and operation are very similar to those of bzip2. A file compressed by gzip is marked with a .gz filename extension. Linux stores manual pages in gzip format to save disk space; likewise, files you download from the Internet are frequently in gzip format.

To gzip all the files in current directory, we can use for command. The below example will gzip all the files from /var/log/audit directory.

gzip all the files

1. Change the directory to audit logs as follows:

# cd /var/log/audit

2. Execute the following command in the audit directory:

# pwd
/var/log/audit
# ls
audit.log  audit.log.1  audit.log.2  audit.log.3  audit.log.4
# for LOG in audit*
do 
    gzip $LOG
done

3. This will zip all the files in audit directory. Verify the gzipped log file in the /var/log/audit directory:

# ls
audit.log.1.gz  audit.log.2.gz  audit.log.3.gz  audit.log.4.gz  audit.log.gz

Unzip all files

1. To unzip all the files in one go, execute the following command:

# for LOG in audit*
do 
    gunzip $LOG
done

Verify the unzipped files in the directory:

# ls
audit.log  audit.log.1  audit.log.2  audit.log.3  audit.log.4

gzip specific files only

To gzip some specific files only, use the below gzip command:

# gzip -c file file1 test > gzip.gz

This will create the gzip.gz file in the current directory which includes the files specified with -c option.

Related Post