- Unsupervised Learning
- Posts
- A tar Primer
A tar Primer
tar is one of the tools we use often and tend to ignore the usefulness of. Here are some of the most common uses as well as some more nifty options. So the first thing you need to know about it is tar‘s main purpose. tar is short for “tape archive” (from back in the olden days), and it basically collects many things into one.
So if you have a directory full of 37 items, when you tar it up you’ll have just one tar file containing all those things, which makes it easier to distribute. Plus, it preserves your directory structure and can also be made to keep permissions and date/time information intact as well.
Options
Here are some of the most commonly used switches:
-c : Create an archive
-f : Create a file from the output (otherwise it goes to the terminal)
-x : Extract an archive
-j : Use bzip2 compression
-z : Use gzip compression
-p : Preserve permissions when extracting (ignores mask)
-t : Get a table of contents from the archive
-v : Show what’s happening as it happens
-d : Diff the archive vs. the filesystem
Examples
Creating an Archive
# create an archive of a directory
tar cf directory.tar directory/
# create an archive of a bunch of files
tar cf directory.tar file1 file2 file3
# tar only the .mp3s in the current directory into a bzip compressed archive
tar -cvf mp3collection.tar ./*.mp3
# create an archive of the /home/daniel/ directory while preserving permissions
tar cvpf daniel.tar /home/daniel/
# create an archive of the /etc directory, but exclude the apache2 directory
tar cvf etc_without_apache.tar –exclude=’/etc/apache2/’
Using Compression
# create a bzip2 compressed archive, verbosely
tar cjvf directory.tar.bz2 directory/
# create a gzip compressed archive, verbosely
tar czvf directory.tar.gz directory/
List the Contents of an Archive
# view the contents of the directory archive
tar tvf directory.tar.bz2
... bluewaters_1440x900.jpg cloudyday_1440x900.jpg fragile_1600x1200.jpg coolemoticon_1440x900.jpg cloudyday_1440x900.jpg ...
Extracting Archives
# extract the directory archive, verbosely 1
tar xvf directory.tar.bz2
Unsupervised Learning — Security, Tech, and AI in 10 minutes…
Get a weekly breakdown of what's happening in security and tech—and why it matters.
# extract only the passwd file out of the etc.tar.bz2 archive
tar xvf etc.tar.bz2 passwd
# extract only the passwd file out of the etc.tar.bz2 archive
tar xvf etc.tar.bz2 passwd
# extract only the postfix directory out of the etc.tar.bz2 archive
tar xvf etc.tar.bz2 /etc/postfix/
# extract only the php files out of the htdocs.tar.bz2 archive
tar xvf htdocs.tar.bz2 –wildcards ‘*.php’
Diffing
# diff the archive against the filesystem
tar df directory.tar.bz2
Notes
1 Both with extracting and diffing, passing the option for compression is optional in most modern versions of tar.2 Can’t go wrong with the man page.