Tar: create archive exclude directories except one

2019-06-15 08:21发布

I have some directories with some files

dir_archive/somedir1
dir_archive/somedir2
dir_archive/somedir3
dir_archive/mydir
dir_archive/mydir/excludedir1
dir_archive/mydir/excludedir2
dir_archive/mydir/excludedir3
dir_archive/mydir/many_other_directories...
dir_archive/mydir/my_archive_dir

I want create tar(gz) archive dir_archive.tar.gz with all files and directories exclude

dir_archive/mydir/excludedir1
dir_archive/mydir/excludedir2
dir_archive/mydir/excludedir3
dir_archive/mydir/many_other_directories...

but include

dir_archive/mydir/my_archive_dir

I dont want use --exclude for each directory

tar cvfz dir_archive.tar.gz --exclude=dir_archive/mydir/excludedir1 --exclude=dir_archive/mydir/excludedir2 --exclude=dir_archive/mydir/excludedir3

I try use --add-file, but it doesn't work:

tar cvfz dir_archive.tar.gz --exclude=dir_archive/mydir --add-file=dir_archive/mydir/my_archive_dir dir_archive

Exists some simple way? Thanks

1条回答
SAY GOODBYE
2楼-- · 2019-06-15 08:30

One way would be first excluding the mydir and then appending the my_archive_dir

tar cvf dir_archive.tar --exclude=dir_archive/mydir dir_archive
tar rvf dir_archive.tar dir_archive/mydir/my_archive_dir
gzip dir_archive.tar

Unfortunately appending doesn't work with zipped archives.

The --exclude option takes a pattern as argument, so if the names of the dirs to be excluded are similar, you can avoid them and still include the archive dir

tar cvfz dir_archive.tar.gz --exclude=dir_archive/mydir/exclude* dir_archive

It is also possible to create a file with names of all the files that you want included and give that list to tar with option -T or --files-from (or in similar fashion list the files to be excluded and give the list with option -X).

filelist.txt:
dir_archive
dir_archive/temp1
dir_archive/mydir
dir_archive/mydir/temp2
dir_archive/mydir/my_archive_dir
dir_archive/mydir/my_archive_dir/temp7
tar cvfz dir_archive.tar.gz --no-recursion --files-from filelist.txt
查看更多
登录 后发表回答