Extract single file from tar to other folder

aixdirectoryscriptingtar

I've searched for multiple forums for this questions and have seen different answers but so far, nothing have worked yet even from the ones I've seen here.

I want to extract a single file from a tar to a different directory.

I've tried this:

tar xvf file.tar -C /home/dir/ filename

or this:

tar -x filename -f file.tar -C /home/dir

But got these errors respectively:

x filename, 14826 bytes, 29 media blocks.
File -C not present in the archive.
File /home/dir not present in the archive.

and:

tar: /dev/rmt0: A file or directory in the path name does not exist.

The first extracted the file but in the same directory, not to the folder I wanted.

Best Answer

In most versions of tar, there are two different modes, depending on whether you put a minus before your options.

The top of the AIX tar man page summarizes the differences:

Berkeley Standards:

tar {c|r|t|u|x} ... [ Archive ] Directory | File ...

X/Open Standards:

tar {-c|-r|-t|-u|-x} ... [-f Archive] ... [-C Directory] File | Directory...

Without the minus, tar works in Berkeley compatibility mode. In this mode, the options don't follow now-standard UNIX command line conventions. Instead, all the flags must be placed together (in any order). The f flag means that the first word after the flags is a file name that should be used instead of the tape drive, /dev/rmt0. (The t in tar stands for tape, and the defaults reflect this.) Also note that there is no -C option in compatibility mode.

With the minus, tar works like most UNIX commands. All the flags (and their arguments) must be specified first, then the non-flags come after. -f takes a file name as an argument (essentially, the file name belongs to the -f flag), so the file.tar must come immediately after the -f. That's why the man page says [-f Archive] with Archive next to the -f. But -x takes no arguments (filename does not belong to the -x). Again, looking at the man page, filename in your example corresponds to File | Directory..., which are all the way at the end of the command line.

The fixed versions of your commands look like

(cd /home/dir; tar xvf /path/to/file.tar filename)

and

tar -x -f file.tar -C /home/dir filename

GNU tar does something similar. The Three Option Styles does a good job of explaining the differences.

Related Question