Back to TIL
shell

Undoing an Unzip That Messed Up My Directory

Every so often, I unzip a file using the command line:

unzip archive.zip

Sometimes, this messes up my current directory completely due to the zip not containing everything inside in a folder. Luckily, there’s a way to clean this mess up.

The cowboy method

This is the YOLO method. You will quickly see why:

  1. List the contents to verify what was inside:
unzip -Z1 archive.zip
  1. Remove:
unzip -Z1 archive.zip | xargs -d '\n' rm -rfv --

This blindly passes the filenames on to rm -rf, which is a bad idea in most cases. So, YOLO.

The secure method

You can also do it like so:

# Write the contained filenames into a list
unzip -Z1 archive.zip > delete-list.txt
# Review the file list manually
nano delete-list.txt
# Only then delete:
xargs -a delete-list.txt rm -rfv --

Less YOLO, more safety.

Prevention

To avoid this in the future, I should always extract ZIP files into a dedicated directory:

unzip archive.zip -d extracted/