-2

I want to tar all directories in a single directory to tar files named after themselves, so for example this directory of directories with tar-all.sh

dir___
      |- dirA
      |- dirB
      |- tar-all.sh

becomes

dir___
      |- dirA.tar.tgz
      |- dirB.tar.tgz
      |- tar-all.sh
  • Go ahead and post the code you've written so far, so we can point you in the right direction. – Emmanuel Rosa Aug 10 '18 at 23:32
0

Use a for loop:

#!/bin/bash

for f in *
do
    echo "Creating tarball of $f..."
    tar -zcf $f.tar.gz $f
done

Results in:

> ./tar-all.sh
> Creating tarball of tar-all.sh...
> Creating tarball of dirA...
> Creating tarball of dirB...
> DONE!

  |- dirA.tar.tgz
  |- dirB.tar.tgz
  |- tar-all.sh.tar.gz
0

The following will find and archive all the dir directory's subdirectories (deleting the original subdirectories).

for subdir in dir/*/; do
    dirname="$( basename "$subdir" )"
    ( cd "$dir" && tar -cz -f "$dirname.tgz" "$dirname" && rm -rf "$dirname" )
done

The pattern dir/*/ will only match the pathnames of the subdirectories under dir and no non-directories, due to the / at the end.

Alternatively, using the -C option of tar instead of an explicit cd:

for subdir in dir/*/; do
    dirname="$( basename "$subdir" )"
    tar -cz -f "dir/$dirname.tgz" -C dir "$dirname" && rm -rf "$subdir"
done

Testing:

$ tree
.
`-- dir
    |-- a
    |   `-- file
    |-- b
    |   `-- file
    |-- c
    |   `-- file
    `-- complicated name
        `-- file

5 directories, 4 files

(run any of the two loops here)

$ tree
.
`-- dir
    |-- a.tgz
    |-- b.tgz
    |-- c.tgz
    `-- complicated name.tgz

1 directory, 4 files

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.