4

I was using the answers from Copy files without losing file/folder permissions question, when I ran across this interesting and unexpected behavior.

Using tar cvpfz target.tar.gz dir1 works perfectly, and it is basically the structure of the commands listed in the suggested answers to the question linked above.

Strangely, however, when I added the optional - before the parameters, (i.e. tar -cvpfz ..., thinking it was just a stylistic change), that's where the strangeness ensues.

$ tar -cvpfz target.tar.gz dir1
tar: target.tar.gz: Cannot stat: No such file or directory
...
tar: Exiting with failure status due to previous errors

Even stranger, although tar -cvpfz ... throws the aforementioned error, the command actually works, but instead of creating a gzipped file, it creates a tar file with the name z (even though it still throws the error).

If I do a tar -tvf z, it lists the contents of the tar correctly. If I do a tar -ztvf z, it says that it is not gzipped.

I finally found that changing the command to tar -zcvpf works perfectly. Somehow, putting the z parameter first works correctly, however putting it last (i.e. tar -cvpfz ...) does not!

man tar seems to indicate that the - is optional, and one would think the tar command should work identically with or without the -.

Hopefully this will help someone else who, like me, added the -, thinking it was just a stylistic difference that wouldn't change the command.

Since I am curious, and would love to learn more about this, can anyone shed light on why this happens?

2 Answers2

3

The -f option should be followed by a file or device name. When using tar cvpfz target.tar.gz dir1 you are actually using the so-called "Old Option Style" where

When options that need arguments are given together with the command, all the associated arguments follow, in the same order as the options. (tar info page)

1

Muru really answered the question with the links he posted, but due to his encouragement, I will re-copy one of his links and recap my comments here to hopefully make it easier to see the answer.

According to this StackExchange link, the f parameter for the tar command is somewhat special, as it requires an argument (an archive filename) that immediately follows the f parameter, if you are preceding your parameters with a - (e.g. tar -cf). However, as the answer in the link mentions, it may be safer to just forgo the -, so the f parameter doesn't risk treating any parameters you may put after the f as a filename.

This was the problem I ran into as stated in my question, since I tried to put the z parameter right after the f (e.g. tar -cvpfz) which caused the tar command to greedily 'consume' the z and treat it as the archive filename argument to the f parameter, rather than treating the z as simply the tar command's gzip parameter.

In brief, by omitting the - (e.g. using tar cvpfz ... rather than tar -cvpfz ..) the problem that I encountered can be avoided. Now I know why. Thanks, muru!