Mint Mint - 6 months ago 30
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

apt-get
)

Currently I have this:

wget http://nginx.org/download/nginx-1.0.0.tar.gz
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

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!)

Comments