How do you gzip a directory in Linux? It’s definitely not using the gzip command because if you try to compress a folder using gzip command, you’ll see this error:
gzip: target is a directory -- ignored
Interesting, isn’t it? gzip command cannot compress a directory because essentially, gzip works on individual files, not the entire folder.
What can you do now? How to gzip compress a file in Linux? Here’s what you can do.
gzip a directory using tar command
Instead of trying to compress the folder directly, you should use tar on it first. The tar command will collate all the files into one archive file. It doesn’t compress the file itself.
If you combine tar with gzip, the tar command will create one single archive file from the folder and then gzip will compress this archive file.
The good thing is that you can do both of these steps in one single command by using the z option. The command looks something like this:
tar -zcvf output_file_name directory_to_compress
Let me explain the options used in the above command to you:
- z – tells tar that it is dealing with gzip file
- c – tells tar to compress the file
- v – verbose mode showing what files are being processed
- f – output is a file
Example of using tar and gzip to compress a folder
Let’s say I have a bunch of files in a directory. If I use the du command to get the size of the directory, it’s 204KB.
du -sh sample_text_files
Now if I gzip compress the folder:
tar -cvzf sample_text_archive sample_text_files
Now if I check the size of the compressed folder using ls command, it’s hardly 10KB.
ls -lh sample_text_archive
-rw-r--r-- 1 abhishek abhishek 9.6K Apr 11 11:41 sample_text_archive
Keep in mind while using tar and gzip command
You should note a couple of things while using the tar command:
It’s important to provide the filename in the command otherwise you’ll see this error:
tar: Cowardly refusing to create an empty archive
Try 'tar --help' or 'tar --usage' for more information.
If you don’t use the option -f at all, you will still see an error, a different one this time.
tar: Refusing to write archive contents to terminal (missing -f option?)
tar: Error is not recoverable: exiting now
I hope this command helped you to gzip a directory in Linux and you also learned a few related things around tar and compression. Now that you know how to compress a folder, maybe you would like to read on how to extract tar xz file in Linux.
Any questions, suggestions of a simple word of thanks are always welcomed.