Let's assume I've a ZIP file whichs content may look like

# file: with_out_dir.zip
- file_in_subdir.txt

but it may also look like this

# file: with_dir.zip
- file1.txt
- file2.cpp
- file3.js
- some_sub_dir/
-- file_in_subdir.txt
- file4.xml

and now I would have my bash script extract these files, but in any case it should to be extract to /var/sample/ so it will like this:

# expected output
- sample/
-- file1.txt
-- file2.cpp
-- file3.js
-- some_sub_dir/
--- file_in_subdir.txt
-- file4.xml

What's the best way todo that via a bash script?

At the moment I am using unzip to extract zip files, but I'm open for any other command line tool, if it would be easier using it.

2 Answers 2


I would suggest simply:

  • Extract into a fresh new directory
  • If, after extraction, the new directory contains exactly one subdirectory, then move all of the files inside it up one level and get rid of the original subdirectory.

By the way, making an archive (tar, zip, whatever) without having all of the members of the archive inside of a subdirectory is EVIL. I don't know why people do it!


There are several smart extraction tools out there (which I found out after I wrote one for myself). You may want to look at dtrx ( install with sudo apt-get install dtrx).

dtrx always creates the toplevel directory if that is not yet in the archive. Adapting your bash wrapper script (that calls dtrx instead of unzip) then becomes much more simple as it only has to move away the subdirectories and remove the toplevel directory (as the latter is always there).

  • Thanks for that tipp. dtrx always creates a directory with the name of the ZIP file (just removing the extension), so it's even easier to store it to /var/sample.zip and then extract it.
    – miho
    Commented Oct 12, 2014 at 16:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .