Linux – Using bash to extract files in Linux results in an error when the path contains spaces

Using bash to extract files in Linux results in an error when the path contains spaces… here is a solution to the problem.

Using bash to extract files in Linux results in an error when the path contains spaces

The file path is as follows:
path/path/path/filename 2.3.pdf.zip

What did I do wrong :

# unzip files back to normal
# and remove zip files
for f in `find "$1" -type f -iname "*.zip"`; do
        dir=`dirname "$f"`
        unzip -o "$f" -d "$dir"
        rm -f "$f"
done

Error message:
Unzip: The file, file.zip, or file.ZIP could not be found or opened

Use UnZip 5.52
Red Hat Enterprise Linux Server version 5.10 (Tikanga).

Solution

I think your loop is splitting the output of find based on spaces. You might want to do something to read one line at a time, like this

find "$1" -type f -iname "*.zip" | while read f
do
    dir=`dirname "$f"`
    unzip -o "$f" -d "$dir"
    rm -f "$f"
done

Alternatively, you can set IFS:

IFS='\n'
for f in `find "$1" -type f -iname "*.zip"`; do
        dir=`dirname "$f"`
        unzip -o "$f" -d "$dir"
        rm -f "$f"
done

Related Problems and Solutions