Create one tar file for multiple directories excluding its parent folders

I am working on a bash script shell that creates a tar file for several folders, excluding its parent folders in all directories and also excluding the specified folder.

Directory structure:

$ ls dir1 dir11 testdir $ ls dir2 dir12 testdir2 $ ls dir3 dir13 testdir3 $ tar -cvf file1.tar dir1 dir2 dir3 --exclude="test*" 

The above works great.

But I do not want the folders dir1, dir2 and dir3 to also be in tar. I only need inside files and directories.

So my last tar should contain the following

 $ tar -tvf file1.tar dir11 dir12 dir13 

Can someone help me solve this problem. Thanks inadvance

+5
source share
1 answer

If I understand the question correctly, you can use the -C option (capital C = change directory), for example:

 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:

test window creation

 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} 

now the tree:

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

Tag:

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

tar contents:

 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 else, edit your question.

+14
source

Source: https://habr.com/ru/post/1200314/


All Articles