1

I am trying to untar a file from a shell script. There is one file within the file.tar.gz that is a tar that is not getting untared.

I have tried several methods with no luck.

https://stackoverflow.com/questions/18897060/how-to-extract-a-tar-file-inside-a-tar-file

Extract multiple .tar.gz files with a single tar call

#have tried this
for file in "$MY_TAR"
do
NEWDIR=`echo $file | tr -d [a-zA-Z.]`
mkdir $NEWDIR
tar -xvf $file -C $NEWDIR
done 

# And this
for file in *.tar.gz; do tar -zxf $file; done

#snip -------
for file in "$MY_ZIP"
do
if [ "$file" == "$NESTED_TAR"] ; then
mkdir "$NESTEDTAR_DIR"
tar -xOf "$file" -C  "$NESTEDTAR_DIR" | tar -x
else
tar -xvf "$file"
fi
done

Edit: After untarring with the shell script the contents should be untarred and retained as well as the Nested_Tar.tar to be untarred into it is own named dir.

Sample Input My_Tar:

/Unique_DirNameAfterUnTar
File1
Documents/
Nested_Tar.tar (this is not untaring needs to untar into dir named Nested_Tar)
File2
File3
Another_Documents_Dir/
File4
  • It looks to me like the 1st tar is being extracted to NEWDIR, but the 2nd for-loop tar is being run in the current directory. – Jeff Schaller Mar 6 '16 at 19:49
  • @Jeff Schaller yes, that is correct, regardless, the nested tar is not getting untared. – Upworks Mar 6 '16 at 20:23
  • cd $NEWDIR then run the for/tar... – Jeff Schaller Mar 6 '16 at 20:28
  • Apologies should have been more clear, both examples above do the same thing. – Upworks Mar 6 '16 at 20:36
  • stackoverflow.com/a/18897328/4957508 sounds like what you want, then, if you just add the uncompression. – Jeff Schaller Mar 6 '16 at 22:06
0

Here's a script that will extract a top-level tar.gz file (My_Tar.tar.gz) into $NEWDIR, then loop through the extracted contents and extract any discovered tar files into directories based on those tar file names. If the nested tar files were created 'above' their contents (so that, for example, Nested_Tar.tar has "Nested_Tar/" as a subdirectory already), then you could skip the mkdir part below as well as the -C "$d" option to the inner tar.

NEWDIR=output
tar -xz -C $NEWDIR -f ../My_Tar.tar.gz
(cd $NEWDIR;
for f in *.tar
do
  d=$(basename "$f" .tar)
  mkdir "$d" && tar -x -C "$d" -f "$f"
done
)

I used a subshell just to keep your existing shell's pwd in the cwd; if you'd rather end up inside $NEWDIR, just remove the outer parenthesis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.