Output the root directory in a tar archive Output the root directory in a tar archive shell shell

Output the root directory in a tar archive


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


Using sed as described in the other answer is a good approach, but it's better to use head -1 before sed instead of uniq after; this has much better performance - you are pumping only the first line through sed and this also avoids the requirement of uniq to load the entire output of sed into memory. Furthermore, if the tar contains multiple top level directories, this will return the first top level directory, whereas uniq will give you all top level directories.

tar tzf nginx-1.0.0.tar.gz | head -1 | sed -e 's/\/.*//'

I personally find it more readable to escape the internal / in the pattern match of sed as \/ rather than introducing another delimiter such as @, but that's just a matter of preference


Many of the above answers are correct, but I encounter a situation where the actual tar stopped as a result of piping to head.

The following command in Borne shell:

tar -v -zxf plotutils-3.1.tar.gz | head -1 | cut -d "/" -f 1

Will produce the top directory name: plotutils-3.1However, the resulting directory will be either empty or containing one item.I am using ubuntu. To get the actual result of the tar you have to do another command

tar -zxf plotutils-3.1.tar.gz  

again. I am not sure I am doing something wrong here; but this should be noted. I found this out when trying to write a shell script to automatically run the autotool's configure script. Hope this may help others.