Search code examples
bashpattern-matchingunzipglob

Bash script of unzipping unknown name files


I have a folder that after an rsync will have a zip in it. I want to unzip it to its own folder(if the zip is L155.zip, to unzip its content to L155 folder). The problem is that I dont know it's name beforehand(although i know it will be "letter-number-number-number"), so I have to unzip an uknown file to its unknown folder and this to be done automatically.

The command “unzip *”(or unzip *.zip) works in terminal, but not in a script. These are the commands that have worked through terminal one by one, but dont work in a script.

#!/bin/bash
unzip * #also tried .zip and /path/to/file/*  when script is on different folder
i=$(ls | head -1)
y=${i:0:4}
mkdir $y
unzip * -d $y

First I unzip the file, then I read the name of the first extracted file through ls and save it in a variable.I take the first 4 chars and make a directory with it and then again unzip the files to that specific folder.

The whole procedure after first unzip is done, is because the files inside .zip, all start with a name that the zip already has, so if L155.ZIP is the zip, the files inside with be L155***.txt.

The zip file is at /path/to/file/NAME.zip. When I run the script I get errors like the following:

unzip: cannot find or open /path/to/file/*.ZIP
unzip: cannot find or open /path/to/file//*.ZIP.zip
unzip: cannot find or open /path/to/file//*.ZIP.ZIP. No zipfiles found. 
mkdir: cannot create directory 'data': File exists data 
unzip: cannot find or open data, data.zip or data.ZIP.

Solution

  • I would try the following.

    for i in *.[Zz][Ii][Pp]; do
        DIRECTORY=$(basename "$i" .zip)
        DIRECTORY=$(basename "$DIRECTORY" .ZIP)
        unzip "$i" -d "$DIRECTORY"
    done
    

    As noted, the basename program removes the indicated suffix .zip from the filename provided.

    I have edited it to be case-insensitive. Both .zip and .ZIP will be recognized.