Shell – Bash loop unzip passworded file script

linuxpasswordshell-scriptzip

I'm trying to make a script that will unzip a password protected file, the password being the name of the file that I will get when unzipping

Eg.

file1.zip contains file2.zip and it's password is file2.

file2.zip contains file3.zip and it's password is file3

How do I unzip file1.zip, and read the name of file2.zip so it can be entered in the script?

Here's a screenshot of what I meant, I just need bash to read that output in order to know the new password
(In this case the password is 13811).

Here's what I've done so far

    #!/bin/bash

    echo First zip name:
    read firstfile


    pw=$(zipinfo -1 $firstfile | cut -d. -f1)
    nextfile=$(zipinfo -1 $firstfile)
    unzip -P $pw $firstfile

    rm $firstfile
    nextfile=$firstfile

Now how can I make it do the loop?

Best Answer

If you don't have and cannot install zipinfo for any reason, you can imitate it by using unzip with -Z option. To list the contents of the zip use unzip -Z1:

pw="$(unzip -Z1 file1.zip | cut -f1 -d'.')" 
unzip -P "$pw" file1.zip

Put it to a loop:

zipfile="file1.zip"
while unzip -Z1 "$zipfile" | head -n1 | grep "\.zip$"; do
    next_zipfile="$(unzip -Z1 "$zipfile" | head -n1)"
    unzip -P "${next_zipfile%.*}" "$zipfile"
    zipfile="$next_zipfile"
done

or a recursive function:

unzip_all() {
    zipfile="$1"
    next_zipfile="$(unzip -Z1 "$zipfile" | head -n1)"
    if echo "$next_zipfile" | grep "\.zip$"; then
        unzip -P "${next_zipfile%%.*}" "$zipfile"
        unzip_all "$next_zipfile"
    fi
}
unzip_all "file1.zip"

-Z zipinfo(1) mode. If the first option on the command line is -Z, the remaining options are taken to be zipinfo(1) options. See the appropriate manual page for a description of these options.

-1 : list filenames only, one per line. This option excludes all others; headers, trailers and zipfile comments are never printed. It is intended for use in Unix shell scripts.

Related Question