The tar utility is used to combine multiple files or directories into a single file. This allows for easy backup to remote systems or to just have a backup copy on the local machine should you need one. The ability to compress via bzip2, gzip or xz is built into the utility allowing you to compress the file as well.
The tar utility is pretty simple to use, however it has several command options, which can be a bit difficult to remember. Below are some of the more common command options.
to simply create a tar file (known as tarballs) of a single file (kinda pointless, but just for demonstration) you would use the following command:
tar -cf filename.tar <filename>
Example:tar -cf backup_report.tar report.txt
The options “-cf” essentially says “Create File”. As stated, since that creates a tarball of one single file, it’s not that useful. However, if you add the -j option it makes more sense.
Using -cfj creates a compressed file using the Bzip2 utility.
tar -cjf compressed_report.tar.bz2 report.txt
This creates a compressed version of the report.txt file under the name compressed_report.tar.bz2 in the same directory.
One important thing to note is that the “f” must come at the end of the set of flags/options. If you do “-cfj newfile.tar.bz2 oldfile.txt” with the “f” in the middle tar reads that as “Create File ‘j’ from newfile.tar.bz2”. It’ll create an empty file with the name ‘j’ and give an error because it can’t find the file “newfile.tar.bz2”.
To create a tarball from an entire directory you would do something similar:
tar -cjf backup_of_Documents.tar.bz2 Documents
This makes a backup of all of the files and subdirectories in the Documents directory located at /home/<username>. Just make sure you’re currently in that directory when you type this command. If not, you’ll have to type the full path:
tar -cjf backup_of_Documents.tar.bz2 /home/<username>/Documents
One additional flag that is often used is the -v option. This turns on the “verbose” output. This will show files as they’re being processed. If you’re creating a compressed file of a directory that contains several large files and you do not turn on the verbose option, it can look as though your terminal has hung.
tar -cvjf backup_of_Documents.tar.bz2 Documents
The tar utility has many other options that allows more advanced features. Check out the tar man page by typing “man tar” into your terminal for more information.