If I have a .tar or .tgz or .tbz on my desktop, and I double click on it, I get the folder that was compressed, neatly decompressed right next to the archive file. Just like you'd expect.
When I try to decompress a tarred item via the tar
command, the output I get has the whole full path of the original compressed file.
So for example, if I make a .tbz out of a folder on my desktop called "foo", and then I decompress it via tar -xf foo.tbz ~/Desktop/foo
, what I get is:
/Users/[user]/Desktop/foo/Users/[user]/desktop/foo/bar.txt
Is there some magic flag in tar
that I'm not seeing? I've googled up 'how-to' after 'how-to' that give you a simple tar
command to extract a file, but all the directions I see give me my undesired result with long, unnecessary, super-nested result directors.
Best Answer
The option you are looking for is
--strip-components
(fromman tar
):But it is not 100% equivalent to the way the Finder works: you still need to know the directory depth to strip.
Fortunately, it can be calculated with this command:
Since you have to replace
<tar archive name>
with the name of your tar archive, it is not as convenient as simply double clicking it in the Finder, but it can be useful in Bash scripts.If the tar archive contains several files in different paths, the command above calculates the maximum common directory depth:
For example, if you create a tar file like this:
so that:
you can extract all files (with the shortest directory depth) as follows:
Calculate maximum common directory depth:
Command returns
5
.Run
tar
passing the result of the previous command to--strip-components
:Instead of running two commands, if your shell is
bash
orzsh
, you can use$()
to pass the result directly to--strip-components
:This command also properly deals with the case of a tar archive without a directory hierarchy: