How to untar multiple tarballs to a subdirectory

Written by Johannes on May 30, 2011 Categories: bash-Scripts Tags: 

Your ads will be inserted here by

Easy AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

I often have a batch of *.tgz tarballs lying around waiting for me to be unpacked. Often I want to unpack them into subdirectories, as not all of the tarballs contain subdirectories or they might even have conflicting filenames. The following little bash script does the trick (assuming you want to unpack all tarballs in your working directory):

for i in `ls *.tgz`; do
  DIRNAME=`(echo $i | sed "s/\.tgz//g")`
  if [ -d $DIRNAME ]; then
    echo "Warning, directory exists"
  elif [ -f $DIRNAME ]; then
    echo "Error $DIRNAME is file"
    mkdir $DIRNAME
  tar xf $DIRNAME.tgz
  rm -rf $DIRNAME.tgz
  cd ..

Obviously you can easily tweak the script to accommodate for other formats, more sophisticated error checking… you name it.

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre user="" computer="" escaped="">