David Wright
David Wright

Reputation: 435

Extract .tar File to Current Directory Automatically with Shell Script

I'm totally new to the world of bash, and I'm currently working on a script that will loop through a large directory and extract any .tar files it finds into it's current location.

I'm using the following script:

for a in in /home/davidwright/attachments/*/*.tar
do
  echo "extracting $x"
  tar -xvf $x
done

Currently the file is extracting fine, but it is extracting to the location of my script. I need it to extract within the .tar's current directory.

The solution is probably very simple, but I can't figure it out for the life of me. Thanks!

Upvotes: 4

Views: 4373

Answers (1)

Cyrille
Cyrille

Reputation: 14513

You can try:

-C, --directory DIR
              change to directory DIR

and $(dirname "$x") for file directory

for x in in /home/davidwright/attachments/*/*.tar
do
  echo "extracting $x"
  tar -xvf "$x" -C "$(dirname "$x")"
done

Upvotes: 5

Related Questions