0

I need to create an archive of a directory using tar in a shell script but I am also supposed to exclude hidden files and files whose size is equal to 0. Also the first command line argument is the location of the archive which is supposed to be created, the second is the name of the archive and the third is the path to the directory whose files are supposed to be archived.

I tried sending the arguments like this in my terminal:

/bin/bash ss1 /home/user arch /home/user/folder

But it is giving me some tar errors. I tried to archive like this:

tar -cvf --exclude=.* $1/$2 $3 

But it is not correct and I am not sure what the right syntax for this would be, and also how I would exclude empty and hidden files.

3
  • the command just made an archive called --exclude=.*
    – ivana14
    May 31, 2017 at 11:33
  • You're not able to exclude empty files with tar you will need to make a shell script for that. To exclude a pattern the exclude needs to be placed before the source and destination.
    – JazzCat
    May 31, 2017 at 11:38
  • @JazzCat I am doing all this in a shell script.
    – ivana14
    May 31, 2017 at 11:40

2 Answers 2

7

Since you tagged this linux I'll assume you have GNU find and GNU tar.

If your filenames don't have embedded newlines and you don't want to archive empty directories:

find "$3" -type f \! -empty \! -name '.*' | tar cvf "$1/$2" -T -

find finds the relevant files, and -T - tells tar to read the list of files to archive from stdin.

Refining this, if you want to include empty directories:

find "$3" \( -type d -empty \) -o \( -type f \! -empty \! -name '.*' \) | \
    tar cvf "$1/$2" -T -

And if you also want to handle filenames with embedded newlines:

find "$3" \( \( -type d -empty \) -o \( -type f \! -empty \! -name '.*' \) \) -print0 | \
    tar cvf "$1/$2" --null -T -
0
0

Try this:

find test/ -not -iname ".*" -not -empty -exec tar --no-recursion -rvf file.tar {} \;

The only trouble is that empty directories will not be included, but i think there is some workaround somewhere...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .