Quote:
Originally Posted by sag47
Code:
#!/bin/bash
rootdir="$PWD"
find "$rootdir" -type f -name '*.zip' | while read file;do
cd "$(dirname "$file")"
if [ "$(dirname "$file")" = "$PWD" ];then
mkdir "$(basename "$file" | cut -d. -f1)"
cd "$(basename "$file" | cut -d. -f1)"
unzip "$file"
else
echo "error"
break
fi
done
cd "$rootdir"
|
Here's the new script with comments.
Code:
#!/bin/bash
#assumes you're running the script as ./script.sh and the script is located
#where you need to process the files.
rootdir="$PWD"
#see man find; for more information
find "$rootdir" -type f -name '*.zip' | while read file;do
#change the current working directory to the directory of the zip file
cd "$(dirname "$file")"
#before processing, ensure the current working directory is in fact the same directory where the zip file is located
#this is relative to the zip file and has nothing to do with $rootdir
#the point is you want to be sure the directory change worked before you go unzipping a file
#otherwise it's possible to accidentally unzip all zip files within the same folder if it can't ever change the directory
#alternatively you could also use the following commented out if statement instead which checks the exit status of the last command (which would be the cd command)
#if [ "$?" = "0" ];then
if [ "$(dirname "$file")" = "$PWD" ];then
#added the -p switch to mkdir so that if the directory exists there is no error
#if the directory does not exist then create it; else update the directory timestamp
mkdir -p "$(basename "$file" | cut -d. -f1)"
#make $PWD the directory of the same name of the zip file
cd "$(basename "$file" | cut -d. -f1)"
#$file is a full path name and not a relative path.
#unzipped $file will output to the current working directory
unzip "$file"
else
#since there was an error "break" out of the while loop and stop processing zip files.
echo "error"
break
fi
done
#I added this at the end in case you want to do post processing after the while loop
#if this isn't here then the script would be working in the last used working directory (which is the last zip file unzipped)
#this may or may not be what you expect so instead of guessing I added this in to force changing the directory back to $rootdir
cd "$rootdir"
Basically I took advantage of unzip outputting to the current working directory. That's why this script works. There are other more short hand ways of doing this but I decided to approach it in a way that was conceptually easy to understand.
If you want to learn more about a script use the man pages. man every command you see and that is how you will learn. I suggest starting with man bash.
Alternatively you could also avoid errors with making the directory like so...
Code:
if [ ! -d "$(basename "$file" | cut -d. -f1)" ];then
mkdir "$(basename "$file" | cut -d. -f1)"
fi
cd "$(basename "$file" | cut -d. -f1)"
unzip "$file"
SAM