Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a single tar file for multiple directories by excluding its parent folders

Tags:

linux

shell

tar

I'm working on a bash shell script which creates a tar file for multiple folders by excluding its parent folders to all the directories and also exclude specified folder.

The directory structure is:

$ ls dir1
dir11 testdir

$ ls dir2
dir12 testdir2

$ ls dir3
dir13 testdir3

$ tar -cvf file1.tar dir1 dir2 dir3 --exclude="test*"

The above works fine.

But I dont want the dir1, dir2 and dir3 folders also in tar. I need only inside the files and directories.

So my final tar should contain as following

$ tar -tvf file1.tar
dir11 dir12 dir13

Can anyone help me out to solve this one. Thanks inadvance

like image 290
user27 Avatar asked Aug 14 '14 10:08

user27


People also ask

How can I create a tar file without directory?

One way is to use the -C option of the tar command. We can envisage the operation of the tar command with the -C option as two steps: Change the current directory to the one given by the -C option. Archive the specified files in the new current directory.


1 Answers

If I understand right the question, you can use the -C (capital C = change directory) option, e.g:

tar cvf /tmp/some.tar -C /path/to/dir1 . -C /path/to/dir2 .    #multiple -C allowed

check it with

 tar cf - -C /path/to/dir1 . -C /path/to/dir2 .  | tar tvf -

Example:

createing a testcase

cd /tmp
mkdir test
cd test
mkdir -p {dir{1..3},testdir}
touch dir1/file{1..3} dir2/file{4..6} dir3/file{7..9}

the tree is now:

$ find . -print
.
./dir1
./dir1/file1
./dir1/file2
./dir1/file3
./dir2
./dir2/file4
./dir2/file5
./dir2/file6
./dir3
./dir3/file7
./dir3/file8
./dir3/file9
./testdir

The tar:

tar cf - -C dir1 . -C ../dir2 . -C ../dir3 . | tar tvf -

the tar content is:

drwxr-xr-x  0 jm    staff       0 14 aug 13:07 ./
-rw-r--r--  0 jm    staff       0 14 aug 13:07 ./file1
-rw-r--r--  0 jm    staff       0 14 aug 13:07 ./file2
-rw-r--r--  0 jm    staff       0 14 aug 13:07 ./file3
drwxr-xr-x  0 jm    staff       0 14 aug 13:08 ./
-rw-r--r--  0 jm    staff       0 14 aug 13:10 ./file4
-rw-r--r--  0 jm    staff       0 14 aug 13:10 ./file5
-rw-r--r--  0 jm    staff       0 14 aug 13:10 ./file6
drwxr-xr-x  0 jm    staff       0 14 aug 13:08 ./
-rw-r--r--  0 jm    staff       0 14 aug 13:10 ./file7
-rw-r--r--  0 jm    staff       0 14 aug 13:10 ./file8
-rw-r--r--  0 jm    staff       0 14 aug 13:10 ./file9

If you want something other, please edit your question.

like image 73
jm666 Avatar answered Sep 20 '22 10:09

jm666