Unzipping Multiple Zip Files to Folders in Linux

This is a quick tip for you if you find yourself in a situation in which you want to unzip a large number of zip files but do so into their own directories, on Linux. Ironically, on windows, you can usually find a shortcut on the desktop which will do this through the GUI - that’s not something you normally find! To begin, as you may know, typing:

unzip file.zip

will extract the zip archive into the current directory. That’s OK but if you have two zip files and do this:

unzip file-1.zip
unzip file-2.zip

They intermingle - not a pretty sight. To force them to extract into their own directories instead of the current one, you can instead do:

unzip file-1.zip -d dir-1
unzip file-2.zip -d dir-2

That’s better, right? But if you had hundreds of zip files and you wanted to do that to all of them, that would lead to RSI and a sad face. There has to be an easier way, and as usual, there is. This one-liner will take care of it for you:

ls *.zip | while read f; do unzip -d `basename $f .zip` $f; done

Let’s break it down into its constituent parts. Firstly, we list all the zip files with “ls *.zip”. The output of that will be something like this:

file-1.zip file-2.zip file-3.zip and so on...

Next, we pipe that output to a while loop which will do everything we ask it to do (between the do and done section) for each of the entries we pass it. But what are we asking for? In this case, we’re working out what the name of the directory should be by stripping off the “.zip” using the basename command. As an example:

basename file-1.zip .zip

produces:

file-1

Here, we use the backticks (`) to grab the output of the command and use that with the “-d“ option I mentioned earlier. Lastly, we specify the zip file itself ($f).

All done. See what I do with this in my next post because I had a specific reason I wanted it.


Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com