Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a .tgz into specific subfolder only if there are files in the tar that would extract to my CWD

Tags:

bash

tar

Most tar files extract into their own subfolder (because the people that write open source utilities are amazing people).

Some extract into my cwd, which clutters everything up. I know there's a way to see what's in the tar, but I want to write a bash script that essentially guarantees I won't end up with 15 files extracted into my home folder.

Any pointers?

pseudo code:

if [listing of tar files] has any file that doesn't have a '/' in it:
    mkdir [tar filename without extension]
    tar xzvf [tar filename] into [the new folder]
else:
    tar xzvf [tar filename] into cwd

EDIT:

Both solutions are great, I chose the below solution because I was asking for a bash script, and it doesn't rely on extra software.

However, on my own machine, I am using aunpack because it can handle many, many more formats.

I am using it with a shell script that downloads and unpacks all at once. Here is what I am using:

#!/bin/bash
wget -o temp.log --content-disposition $1
old=IFS
IFS='
'
r=`cat temp.log`
rm temp.log
for line in $r; do
    substring=$(expr "$line" : 'Saving to: `\(.*\)'\')
    if [ "$substring" != "" ]
    then
        aunpack $substring
        rm $substring
        IFS=$old
        exit
    fi
done
IFS=$old
like image 204
Jeff V Avatar asked Dec 27 '22 13:12

Jeff V


1 Answers

The aunpack command from the atool package does that:

aunpack extracts files from an archive. Often one wants to extract all files in an archive to a single subdirectory. However, some archives contain multiple files in their root directories. The aunpack program overcomes this problem by first extracting files to a unique (temporary) directory, and then moving its contents back if possible. This also prevents local files from being overwritten by mistake.

like image 71
adl Avatar answered Jan 13 '23 13:01

adl