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
Upworks
  • 13

1 Answers1

1

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.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255