The question is published on by Tutorial Guruji team.
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.
Since you tagged this
linux I’ll assume you have GNU
find and GNU
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
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 -