Mint Mint - 2 years ago 109
Bash Question

Output the root directory in a tar archive

I'm trying to automate the process you go through when compiling something like nginx using a shell script. (I don't want to use


Currently I have this:

tar xf nginx-1.0.0.tar.gz

But next I need to find out what the directory name is from where it extracted too so I can start the configure script.

Answer Source

Use this to find out the top-level directory(-ies) of an archive.

tar tzf nginx-1.0.0.tar.gz | sed -e 's@/.*@@' | uniq

sed is invoked here to get the first component of a path printed by tar, so it transforms

path/to/file --> path

It does this by executing s command. I use @ sign as a delimiter instead of more common / sign to avoid escaping / in the regexp. So, this command means: replace part of string that matches /.* pattern (i.e. slash followed by any number of arbitrary characters) with the empty string. Or, in other words, remove the part of the string after (and including) the first slash.

(It has to be modified to work with absolute file names; however, those are pretty rare in tar files. But make sure that this theoretical possibility does not create a vulnerability in your code!)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download