How to extract multiple archives with a shell script

I had the problem to extract multiple .tar files (all in the same folder). Doing this by hand was kind of annoying and because i like the heuristic not to do same things more then three times, i wrote a little bash script. The script takes the archive type i.e. .tar, .tar.gz as first parameter and then automatically extracts all the archives files, in the given folder, to subdirectories (foldername of created subdirectory is the basename of the file). So here is the code..maybe it could save a little bit of your time.


#!/bin/bash

for archive in `ls | grep .$1`; do

basename=$(basename $archive)
filename=${archive%.*}

echo "Starting unpacking of ."$1 " file: " $basename
if [ -f $basename ] ; then
echo "Making directory: "$filename
mkdir $filename
echo "Change to directory: "$filename
cd $filename

case $basename in
*.tar.bz2) tar xjf ../$basename ;;
*.tar.gz) tar xzf ../$basename ;;
*.bz2) bunzip2 ../$basename ;;
*.rar) rar x ../$basename ;;
*.gz) gunzip ../$basename ;;
*.tar) tar xf ../$basename ;;
*.tbz2) tar xjf ../$basename ;;
*.tgz) tar xzf ../$basename ;;
*.zip) unzip ../$basename ;;
*.Z) uncompress ../$basename ;;
*.rar) unrar e ../$basename ;;
*) echo "'$basename' cannot be extracted..." ;;
esac
echo "Changing to base directory"
cd ..
echo "Extraced Archive. Basename: "$basename" Filename: "$filename
else
echo "'$basename' is not a valid archive file"
fi
done

Usage (i.e. for .tar archives):

./yourScriptName tar

Update: Added support for multiple archive types.

Have fun :-)

Wenn dir dieser Beitrag gefällt, lade den Autor doch mal zu einem Drink ein ;-)

Broadcast us
  • Yigg
  • Webnews.de
  • Digg
  • MisterWong
  • del.icio.us
  • Technorati
  • DZone
  • Facebook
  • Google Bookmarks
  • Reddit
  • StumbleUpon
  • TwitThis

Tags:

Leave a Reply