Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a shell loop unzip all the files in a directory?

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?

like image 972
helpwithshell Avatar asked Apr 25 '10 16:04

helpwithshell


4 Answers

A few points adding to what others have said:

  • If you put a parameter in single quotes, like in '*.zip', the shell won't do wild card expansion and unzip will try to process an archive that is literally called *.zip
  • Don't use -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.
  • You should check the return code of 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)
like image 85
sth Avatar answered Oct 06 '22 21:10

sth


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
like image 28
Benjamin Bannier Avatar answered Oct 06 '22 19:10

Benjamin Bannier


partly tested:

find . -type d -exec  sh -c "cd \"{}\" ;  unzip \"*.zip\" ; rm \"*.zip\"  "  \;

executes the cd/unzip/rm chain for every subdir.

like image 38
topskip Avatar answered Oct 06 '22 19:10

topskip


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.

like image 35
Mark Byers Avatar answered Oct 06 '22 19:10

Mark Byers