Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unzip ZIP file and extract unknown folder name's content

Tags:

bash

zip

unzip

My users will be zipping up files which will look like this:

TEMPLATE1.ZIP
   |--------- UnknownName
                   |------- index.html
                   |------- images
                               |------- image1.jpg

I want to extract this zip file as follows:

/mysite/user_uploaded_templates/myrandomname/index.html
/mysite/user_uploaded_templates/myrandomname/images/image1.jpg

My trouble is with UnknownName - I do not know what it is beforehand and extracting everything to the "base" level breaks all the relative paths in index.html

How can I extract from this ZIP file the contents of UnknownName?

Is there anything better than:

1. Extract everything
2. Detect which "new subdidrectory" got created
3. mv newsubdir/* .
4. rmdir newsubdir/

If there is more than one subdirectory at UnknownName level, I can reject that user's zip file.

like image 429
siliconpi Avatar asked Nov 29 '10 07:11

siliconpi


1 Answers

I think your approach is a good one. Step 2 could be improved my extracting to a newly created directory (later deleted) so that "detection" is trivial.

# Bash (minimally tested)
tempdest=$(mktemp -d)
unzip -d "$tempdest" TEMPLATE1.ZIP
dir=("$tempdest"/*)
if (( ${#dir[@]} == 1 )) && [[ -d $dir ]]
    # in Bash, etc., scalar $var is the same as ${var[0]}
    mv "$dir"/* /mysite/user_uploaded_templates/myrandomname
else
    echo "rejected"
fi
rm -rf "$tempdest"
like image 56
Dennis Williamson Avatar answered Oct 10 '22 01:10

Dennis Williamson