I previously wrote a how-to guide to fetching a remote file in Linux. That’s great, but once you’ve got the file, sometimes you’ll need to do some more work with it before you can use it.
This is especially true with archive files. Archives generally come in one of two forms:
- ZIP files – more commonly used on Windows platforms;
- TAR files – more commonly used on Linux and UNIX platforms.
Platforms such as Github and WordPress often offer both ZIP and TAR formats for their downloads.
Once you have the archive file, you need to extract it into a directory. Assuming your file is called wordpress.tar.gz
, and you want to extract it to an existing directory called my-site
in the same directory, you can use the following command:
tar -xvf wordpress.tar.gz -C my-site/
The -x
switch tells tar to extract the files (as you can also use tar to create compressed archives). The -v
switch puts tar into verbose mode, so it prints everything it’s doing to the command line, and the -f
switch is used in conjunction with the filename to set the file to extract the files from. The -C
switch then tells tar to place the extracted files in the directory named at the end of the command.
However, in most cases this will extract the files, but leave the extracted files in a subdirectory. So, in the case of a WordPress archive, the files would be located in my-site/wordpress/
– what if you don’t want the files extracted to a subdirectory?
Not a problem. You can use --strip-components=1
at the end of the command:
tar -xvf wordpress.tar.gz -C my-site/ --strip-components=1
This strips out the top-level directory and leaves the files directly in the my-site
folder.
If it’s a .tar.gz you’ll need to add the -z flag to decompress, eg tar -zxvf filename.tar.gz
(You could, of course, run gunzip filename.tar.gz first instead, but who wants to bother 😉 )
Oh, and sometimes there are bzip2 files (.tar.bz) which need the -j flag…
I know the -z and -j flags are used as filters, but in the case of gzipped files at least, it doesn’t seem to make a difference. The tar commands seems to decompress properly without the flag. Is there a reason the flag should be used? Does it process the file differently?
Without it you’re expecting tar to recognise it automatically, which probably works 99% of the time. It does help with remembering flags consistently when you’re making an archive, as otherwise you might end up with an uncompressed archive 😉 (although it may guess this from the filename these days – not sure)