I've seen loops to unzip all zip files in a directory. However, before I run this, I would rather make sure what I'm about to run will work right:
for i in dir; do cd $i; unzip '*.zip'; rm -rf *.zip; cd ..; done
Basically I want it to look at the output of "dir" see all the folders, for each directory cd into it, unzip all the zip archives, then remove them, then cd back and do it again until there are no more.
Is this something I should do in a single command or should I consider doing this in Perl?
A few points adding to what others have said:
'*.zip'
, the shell won't do wild card expansion and unzip will try to process an archive that is literally called *.zip
-r
as a parameter to rm
if you just want to remove single files. That's just unnecessarily dangerous since any recursive deleting of subdirectories would probably not be intended.unzip
and only remove the zip file if unzipping was successful (for example you could say if unzip *.zip; then rm *.zip; fi
, or even use a explicit for
loop to process the zip files one by one)You should be fine in general. For debugging just prefixing all commands in the loop with echo
will tell you how the variables expand. You can also always use rm -i
to be asked instead of making rm
go ahead with anything with -f
.
The single quotes in your unzip
call will only unzip files named *.zip
, i.e. the *
will not expand. Use double quotes instead (or no quotes at all).
Your loop now assumes that all directories $i
are directly under the current one. A more general solution would be to use the directory stack (pushd
and popd
);
for i in $dir; do
pushd $i
unzip *.zip
rm -rf *.zip
popd
done
partly tested:
find . -type d -exec sh -c "cd \"{}\" ; unzip \"*.zip\" ; rm \"*.zip\" " \;
executes the cd
/unzip
/rm
chain for every subdir.
Use *
to get the contents of the current directory:
for i in *; do cd "$i"; ...etc... ; done
You should also make sure that something is a directory before trying to cd into it. In bash this is done as follows:
if [ -d "$i" ]; then ...etc... ; fi
You should also be careful to check that the unzip operation succeeded before deleting the zip file. There is no need to use recursive force delete for removing a single file.
I think this is pushing the limit for what it sensible to do one a single line. Put it into a shell script and format it on multiple lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With