Shell – Unzip into directory, independent if directory is contained in ZIP

directoryshell-scriptzip

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

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

but it may also look like this

# file: with_dir.zip
archive/
- 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
/var/
- 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.

Best Answer

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!

Related Question