Greg's Blog

helping me remember what I figure out

Compressing Files in Linux

| Comments

Following on from a little piece way back when (De-compressing files in Linux ) here is it’s opposite how to compress files from the command line on a Linux/Unix system. As with decompressing this process can involve two steps. The first is to Tar the file and then for further compression gzip it.

The basic syntax for using tar is: tar cvf filename.tar list_of_files_or_directories. The tar command is followed by a sequence of switches. c stands for creating a newr archive, v for verbosely list files processed and f for use archive device. So if I wanted to archive an entire web site directory called somesite in a file somesite.tar I would type the following command: tar cvf somesite.tar somesite/. Please note that you can also type the following: tar -cvf somesite.tar somesite/. You can look up the full set of switches and options by typing: man tar.

The next step involves using the gzip command. This is a very simple step where all you need to is specify the file you wish to further compress, i.e. gzip filename. And using our example above you would type: gzip somesite.tar, giving you somesite.tar.gz.

And now for the bonus, deleting all those pesky sub directories in my somesite/ example, in one foul swoop. Be careful as to where you are in relation to the folder and also what you are deleting. There is no recourse once this commands executes and you can easily (with the right permissions) delete a lot more then you ever intended to. OK that’s the warning and now the command: rm -rf directory_name/. The switch r stands for recursive and means that it will remove the contents recursively, i.e. it will go into the sub directories and remove their contents. f forces the command to ignore nonexistent files and to never prompt. Incidently if you want to verify the deletion, i.e. be prompted as to which file is being deleted, then leave the f switch of. So back to the example this is what you would type to remove all the contents of the somesite/ directory: rm -rf somesite/.