Take the 2-minute tour ×

I saw the following piece of code in this thread to unzip all the .zip formats in the sub-folders into the corresponding sub-folders. My questions regarding this piece of the code are the following.

(1)Is this a bash script for a batch job?. If so can I run it as sudo bash filename.bat.

(2)How to specify the parent-folder directory in the code. The parent directory contains under all the sub-folders which in turn contains the zipped(compressed) files.

(3)How to modify the code to include other compression formats such as .rar and .7z

 for file in *.zip; do
       dir=$(basename "$file" .zip) # remove the .zip from the filename
       mkdir "$dir"
       cd "$dir" && unzip ../"$file" && rm ../"$file" # unzip and remove file if successful
       cd ..
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted
  1. Yes, that code fragment looks like a bash script. If it is named filename.bat, you should be able to use sudo bash filename.bat to run it.

  2. The code assumes that the current directory is the 'parent folder' which contains all the zipped files. You'll need to modify the code to handle sub-directories containing .zip files. There are numerous ways to do that.

  3. Given a requirement to handle formats other than just .zip files, you'd probably revise the code to use the file names it is given as arguments as the files to uncompress.

This code might work:

for file in "$@"
    dir=$(dirname "$file")
    base=$(basename "$file" .$extn)
    mkdir -p "$dir/$base"
    cd "$dir/$base"
    case $extn in
    zip)   unzip "../$base.$extn";;

Now, in theory, you could extend the list of extensions in the case statement to include other file formats. However, you should be aware that not all compressors also package multiple files. Typically, you have a composite format such as .tar.gz or .tar.xz or .tar.bz2. The corresponding compressors (or decompressors), simply decompress the file (losing the compression suffix) without extracting the data from the .tar file inside. However, if rar and 7z do behave like zip, then you can use:

    case $extn in
    (zip)   unzip "../$base.$extn";;
    (rar)   unrar "../$base.$extn";;  # Or whatever the command is
    (7z)    un7z  "../$base.$extn";;  # Or whatever the command is
    (*)     echo "$0: unrecognized extension $extn on $file" >&2;;

You can also reinstate the code to delete the compressed form of the file if that seems appropriate to you.

share|improve this answer
add comment

Your Answer


