Linux – Shell Command to Tar Directory Excluding Certain Folders

backupbashlinuxtarunix

In Bash 4, I want make a tar.gz with excluded folders, and while tons of answers about this simple case exist, nothing works in my case.

I would like to keep the directory mentioned in exclude, perhaps I can use exclude-tag-under?

  • I've tried:
    tar --exclude="www/cache" --exclude="www/wp-cache"  -vczf "/volume1/Backup/test/asdsdsd/backup104432/testeur_files_www_2023-12-12_10-36-13.tar.gz" --directory="/volume1/Backup/test/asdsdsd/" -- "www"
    

    Extract of verbose tar result, with the excluded directories and content still there:

    ...
    www/Marques/marque-Peugeot-logo.webp
    www/Marques/marque-Volkswagen-logo.png.webp
    www/Marques/Thumbs.db
    www/cache/
    www/cache/contact commercial PlanetVo.txt
    

Best Answer

If you want to keep the directories at the top of each --exclude statement you need to exclude their content. A wildcard will match all files - including "dot" files that are normally not shown.

This should work for you. (I've pulled out your two long paths into variables only so it's a little easier to read)

out='/volume1/Backup/test/asdsdsd/backup104432/testeur_files_www_2023-12-12_10-36-13.tar.gz'
dir='/volume1/Backup/test/asdsdsd'

tar -cvzf "$out" -C "$dir" --exclude='www/cache/*' --exclude='www/wp-cache/*' www
Related Question