0

I am trying to tar files older than 3 days. I reviewed the existing question creating tar file and naming by current date but when I run the script the files do not get modified. Does anyone have some tips?

# Tar files older than 3 days
files=($(find /this/is/my_path/ -type f -mtime +3))
tar -cvfz backup.tar.gz "${files[@]}"
if [ ! -f ${LOGFILE}.tar.gz ]; then
  Error checking
  if [ $? -ne 0 ]; then
     Process_Error $ERROR_SUM "This file had a problem $FILE!"
  fi
fi

}
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 5
    try `-cvzf` you are currently creating a file called `z`. – 123 Apr 24 '17 at 20:42
  • Also, `files=($(find /this/is/my_path/ -type f -mtime +3))` won't work with files with spaces in their names (`some file.txt` will become two entries, `some` and `file.txt`). And `/this/is/my_path/ * IMPORTANT *.txt` will have the first `*` replaced with a list of files in the current directory, and the `*.txt` replaced with a list of text files. – Charles Duffy Apr 24 '17 at 20:48
  • 1
    See: [Find files and tar them (with spaces)](http://stackoverflow.com/q/5891866/3776858) – Cyrus Apr 24 '17 at 20:52
  • @user7915836 BTW, `${LOGFILE}.tar.gz` and `$ERROR_SUM` not being quoted is also potentially problematic -- as http://shellcheck.net/ will detect. And as an aside, consider using lower-case variable names -- see relevant POSIX convention at http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html specifying all-caps names for variable names with meaning to the OS and shell, and reserving names with lowercase characters for application use. (Because setting a shell variable with the same name as an environment variable overwrites the latter, the same convention applies to both). – Charles Duffy Apr 24 '17 at 20:57

1 Answers1

1
files=( )
while IFS= read -r -d '' file; do
  files+=( "$file" )
done < <(find /this/is/my_path/ -type f -mtime +3 -print0)
tar -cvzf backup.tar.gz -- "${files[@]}"
  • As noted in a comment on the question by @123, the argument directly following -f is a filename; in the above, that became z.
  • array=( $(...) ) is innately unreliable: It relies on string-splitting on characters in IFS to find the boundaries between filenames. However, the only character that can't be present in a path is NUL -- and NUL can't be stored in a string (the datatype of IFS). See BashPitfalls #1 (presently, the files=($(find . -type f)) example is second-to-the-last).
Community
  • 1
  • 1
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Why would you answer then mark as duplicate? – 123 Apr 24 '17 at 21:25
  • [Cyrus pointed out the duplicate](http://stackoverflow.com/questions/43597320/how-can-i-tar-files-in-a-directory-with-bash#comment74245275_43597320) after I'd answered. – Charles Duffy Apr 24 '17 at 21:26
  • Eh, fair enough, you must have known it was a duplicate anyway though... – 123 Apr 24 '17 at 21:38