How To Extract a Tar Files To a Different Directory on a Linux/Unix-like Systems
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 the cd command and extract files. This page explains how to extract a tar archive to different directory on a Linux/Unix system using the tar command.
Syntax
Untarring a file can be done using the following syntax. Typical Unix tar syntax:
tar -xf file.name.tar -C /path/to/directory
GNU/tar Linux syntax:
tar xf file.tar -C /path/to/directory
OR
tar xf file.tar –directory /path/to/directory
Extract .tar.gz archive:
tar -zxf file.tar –directory /path/to/directory
Extract .tar.bz2/.tar.zx archive:
tar -jxf file.tar –directory /path/to/directory
Where,
x : Extract files
f : Tar archive name
–directory : Set directory name to extract files
-C : Set dir name to extract files
-j : Work on .tar.gz file format
-z : Work on .tar.bz2 file format
-v : Verbose output i.e. show progress on screen
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
Extract only specific files from a tar archive
You can extract specific files too:
extract only file1, file2, file3
and dir1 to /tmp/data/
tar -xvf $HOME/etc.backup.tar file1 file2 file3 dir1 -C /tmp/data
Extract .tar.gz/.tgz archive to specific folder
To extract a foo.tar.gz (.tgz extension file) tarball to /tmp/bar, enter:
mkdir /tmp/foo
tar -zxvf foo.tar.gz -C /tmp/foo
Extract .tar.bz2/.tbz2/.tb2/.tar.xz archive to specific directory
To extract a foo.tar.bz2 (.tbz, .tbz2 & .tb2 extension file) tarball to /tmp/bar, enter:
mkdir /tmp/bar
tar -jxvf bar.tar.bz2 -C /tmp/bar
Sample outputs:
etc/adduser.conf
etc/apg.conf
etc/appstream.conf
etc/brltty.conf
etc/ca-certificates.conf
etc/debconf.conf
etc/deluser.conf
etc/fuse.conf
etc/fwupd.conf
etc/gai.conf
etc/hdparm.conf
etc/host.conf
etc/kernel-img.conf
etc/kerneloops.conf
etc/ld.so.conf
etc/libao.conf
etc/libaudit.conf
etc/logrotate.conf
etc/ltrace.conf
etc/mke2fs.conf
etc/mtools.conf
etc/nsswitch.conf
etc/pam.conf
etc/pnm2ppa.conf
etc/popularity-contest.conf
etc/resolv.conf
etc/rsyslog.conf
etc/sensors3.conf
etc/sysctl.conf
etc/ucf.conf
etc/updatedb.conf
etc/usb_modeswitch.conf
See tar(1) for more information.