Sometime, you may want to compress all files in a folder (or folders) in Linux into a single file to save space and so that you can back up the file to other media. In Linux, you can use the tar
utilities which is installed in most Linux distribution by default.
GNU ‘tar’ saves many files together into a single tape or disk archive, and can restore individual files from the archive.
What the utility does is actually it creates an archive of the specified files and then compress the archive. Creating an archive of files is like dumping all the files content into a single file and some dictionary data (name and size of each file) so that you can extract files from the archive later on.
How to compress files and folders
To compress files and folders into a single file:
[bash title=”Syntax:”]tar -czvf output-file input-folders-or-files[/bash]
where
- c – create a new archive
- z – filter the archive through gzip
- v – verbosely list files processed
- f – use archive file
- output-file – the output file
- input-folders-or-file – multiple input folders or files
For example, to create a compressed archive file from the /home/user1 and /home/user2 folder:
[bash title=”Example:”]tar -czvf backup.tar.gz /home/user1 /home/user2[/bash]
It is a good practice to put the output file name with tar.gz extension so that we know that the file is created from the tar
utility and it is compressed.
How to decompress and extract files and folders from a compressed tar archive
To decompress files and folders from a compressed tar archive:
[bash title=”Syntax:”]tar -xzvf input-file[/bash]
where
- x – extract files from an archive
- z – filter the archive through gzip
- v – verbosely list files processed
- f – use archive file
- input-file – the compressed archive file
For example, to decompress and extract files from an compressed archive file:
[bash title=”Example:”]tar -xzvf backup.tar.gz /home/user1 /home/user2[/bash]
tar
has many other options and uses as well. Do reading through its man page for more options.
Leave a Reply