0

Here is my file structure. I am currently residing in test2/ directory, and all commands must run from there.

test/
  |_test2/
publish/
  |_subfolder1/
      |_f1
      |_f2
      |_f3
      |_subfolder2/
          |_f4
          |_f5
          |_f6
          |_f7

I need to do the following

  1. Create a tar.gz of subfolder2 (named the same)
  2. remove subfolder2
  3. create a tar.gz of subfolder1 (named the same) including subfolder2.tar.gz
  4. remove subfolder1

In the end the tar structure should look like this

publish/
  |_subfolder1.tar.gz
      |_subfolder2.tar.gz

When I untar each tar.gz in their current path the output should look like this:

publish/
  |_subfolder1.tar.gz
  |_subfolder1/
      |_f1
      |_f2
      |_f3
      |_subfolder2.tar.gz
      |_subfolder2/
          |_f4
          |_f5
          |_f6
          |_f7

I can accomplish this by doing the following:

cd ../../publish/subfolder1
tar -zxf subfolder2.tar.gz subfolder2/
rm -rf subfolder2
cd ../
tar -zxf subfolder1.tar.gz subfolder1/
rm -rf subfolder1
cd ../test/test2

I really dont want my script to be hopping around folders with cd. I tried using the following command instead:

tar -zcf ../../publish/subfolder1/subfolder2.tar.gz -C ../../publish/subfolder1/subfolder2/ .
rm -rf ../../publish/subfolder1/subfolder2/
tar -zcf ../../publish/subfolder1.tar.gz -C ../../publish/subfolder1/ .
rm -rf ../../publish/subfolder1/

This WILL create tarballs, but gets rid of the directories. After untaring them I see the following:

publish/
  |_subfolder1.tar.gz
  |_subfolder2.tar.gz
  |_f1
  |_f2
  |_f3 
  |_f4
  |_f5
  |_f6
  |_f7

How can I achieve keeping the folder paths in the tarball structure without using a bunch of cd commands?

2
  • 1
    It looks like you wanted to do tar ... -C ../../publish/subfolder1/ subfolder2 and tar ... -C ../../publish/ subfolder1.
    – muru
    Apr 13, 2022 at 17:02
  • OH my, yes that was it. I was changing to the wrong directory. THank you!
    – Dave
    Apr 13, 2022 at 17:10

1 Answer 1

1

To archive the contents of foo, change to foo and tar the current directory: -C /some/dir/foo .. To archive the foo directory itself, change to foo's parent directory and tar foo: -C /some/dir foo.

So the commands would look like:

tar -zcf ../../publish/subfolder1/subfolder2.tar.gz -C ../../publish/subfolder1 subfolder2
rm -rf ../../publish/subfolder1/subfolder2/
tar -zcf ../../publish/subfolder1.tar.gz -C ../../publish subfolder1
rm -rf ../../publish/subfolder1/

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .