TransWikia.com

Tar - exclude all files in sub folder but not nested folders

Unix & Linux Asked on December 19, 2021

I need to create a .tgz archive of the following folder

pack
  |
  rest
    |
    vendor (folder)
    |
    ----index.php
    |
    ----info.log
    | 
    another (folder)
    |
    ---index.php
    |
    ---info.log
    |
    ---somefile.someext 
   |
   somefolder1
   |
   somefoldern
   |
   somefiles.somexts

Just issuing an exclude=index.php etc has unwanted consequences: vendor might in turn have a file bearing that name directly or in one of its sub folders. I haven’t been able to establish from the documentation whether I can instruct tar to ignore all file contents in the rest folder but NOT the sub folders under it.

2 Answers

For the benefit of those running into this post here is the solution that works - at least on Ubuntu 14.04. For the folders structure I have shown above issue

tar -zcf pack.tgz --exclude-from=/path/to/excludes.list pack

excludes.list contains, in my case

rest/index.php
rest/info.log
rest/filetoexclude.ext

...essentially a list of files to exclude. Points to note

  • Using an absolute path to excludes.list file makes it easier to compose the command to build the archive via a shell command executed in a scripting language.
  • The excluded files are in the form folder/file.ext, relative to the folder being archived.
  • There should be a newline char immediately after each filename entry. In a text editor it is easy to get a space in just after the filename in which case it will not get ignored.

Answered by DroidOS on December 19, 2021

Just use "another/index.php" as the pattern (or even "rest/another/index.php"):

$ mkdir -p pack/rest/vendor
$ mkdir -p pack/rest/another
$ touch pack/rest/{vendor,another}/index.php
$ tar --create --verbose --file  xx.tar --exclude "another/index.php"  pack/
pack/
pack/rest/
pack/rest/another/
pack/rest/vendor/
pack/rest/vendor/index.php

I found that for more complex selections of tar file contents it is easier to use find with pruning, and, or, etc., and until you can generate the exact list of input. And then pipe that into cpio and its --format=ustar output mode to generate a tar file.

Answered by Anthon on December 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP