How To Extract a Tar Files To a Different Directory on a Linux/Unix-like Systems

Posted on in Categories , , , , , last updated January 8, 2015

I want to extract tar file to specific directory called /tmp/data. How can I extract a tar archive to a different directory using tar command on a Linux or Unix-like systems?

You do not need to change the directory using cd command and extract files. Untarring a file can be done using the following syntax:

Syntax

Typical Unix tar syntax:
tar -xf file.name.tar -C /path/to/directory

GNU/tar syntax:
tar xf file.tar -C /path/to/directory

tar xf file.tar --directory /path/to/directory

Example: Extract files to another directory

In this example, I’m extracting $HOME/etc.backup.tar file to a directory called /tmp/data. First, you have to create the directory manually, enter:

mkdir /tmp/data

To extract a tar archive $HOME/etc.backup.tar into a /tmp/data, enter:

tar -xf $HOME/etc.backup.tar -C /tmp/data

To see a progress pass the -v option:

tar -xvf $HOME/etc.backup.tar -C /tmp/data

Sample outputs:

Gif 01: tar Command Extract Archive To Different Directory Command
Gif 01: tar Command Extract Archive To Different Directory Command

You can extract specific files too use:

tar -xvf $HOME/etc.backup.tar file1 file2 file3 dir1 -C /tmp/data

To extract a foo.tar.gz (.tgz extension file) tarball to /tmp/bar, enter:

mkdir /tmp/bar
tar -zxvf foo.tar.gz -C /tmp/bar

To extract a foo.tar.bz2 (.tbz, .tbz2 & .tb2 extension file) tarball to /tmp/bar, enter:

mkdir /tmp/bar
tar -jxvf foo.tar.bz2  -C /tmp/bar

See tar(1) for more information.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

6 comment

  1. on the specific files example. it didn’t work on my environment unless i moved the -C flag before the explicit file names
    e.g.

    tar -xvf $HOME/etc.backup.tar -C /tmp/data file1 file2 file3 dir1

  2. I’m very curious to know if there is a directory that is common place to install tar in, or no one follows a directory structure?

Comments are closed.