Why can't -z be the last command-line option to be used with tar?

7

3

$ ls one.tar.gz
one.tar.gz
$ tar -xvfz one.tar.gz
tar: z: Cannot open: No such file or directory
tar: Error is not recoverable: exiting now
$ tar -xvzf one.tar.gz
one
$ tar -xzvf one.tar.gz
one
$ tar -zxvf one.tar.gz
one
$

Lazer

Posted 2010-11-17T16:48:09.323

Reputation: 13 841

Answers

16

The -f switch takes an argument (the filename). If z appears after the f then it is taken to be the filename.

tar -xvfz one.tar.gz

is the same as

tar -xvf z one.tar.gz

If you had done this:

tar -xvf -z one.tar.gz

then -z would have been taken as the filename and you'd have gotten a similar error.

This, however, would have worked:

tar -xvz -f one.tar.gz

The GNU tar man page states:

The first argument to tar must be one of the options: Acdrtux, followed by any optional functions. The final arguments to tar are the names of the files or directories which should be archived.

Note that unless input is from stdin or output is to stdout (where appropriate), the the -f filename option and argument must be given. While the man page implies that the order is fixed, in reality the options can be in any order. Even this weird one works (but it may not work in all versions of tar):

tar -v files_to_archive* -f xyz.tar.gz -cz

For portability, it's probably better to stick to the idiomatic argument order and even leave off the hyphen:

tar czvf xyz.tar.gz files_to_archive*

Paused until further notice.

Posted 2010-11-17T16:48:09.323

Reputation: 86 075

z being last and f taking an argument are not mutually exclusive. – None – 2010-11-17T18:00:42.493

That's true, but I didn't say that. Perhaps I should have been more explicit and said "immediately after". – Paused until further notice. – 2010-11-17T18:19:35.813

You didn't say it, but you did begin your sentence with "because", which is an affirmation of his question, which claims z cannot be last, thereby indirectly implying that z cannot be last. Anyway, I am being pedantic. If you remove "because" then your answer is improved IMO. – None – 2010-11-17T18:54:52.133

Pedantic, yes. I took the question to include an implied "in this sequence". Most of the time with tar you see all the switches concatenated rather than separated as you have in your answer. There's no reason a person couldn't do it the way you show, but the idiom is to do it the way it's shown in the first two successful examples in the question: <operation> <option> <option> <file>. The idiom leads to the inference. – Paused until further notice. – 2010-11-17T19:01:42.080

6

z can be used last:

tar -x -v -f foo.tar.gz  -z

But as stated by @Dennis, the f flag takes an argument.

user31752

Posted 2010-11-17T16:48:09.323

Reputation: