[CentOS] Re: how to tell if a file is older than 30 days? -- [practices] find -mtime usage

Bryan J. Smith b.j.smith at ieee.org
Thu Sep 15 16:33:03 UTC 2005

[ We could _really_ use a "practices" list. ;-]

Jerry Geis <geisj at pagestation.com> wrote:
> I am trying to find out how to tell if a given file is 30
> days or older.

Do you mean accessed time (atime), changed attributes time
(ctime) or modification time (mtime)?  I'll assume you want

The find command is extremely powerful.  E.g.,
  find / -mtime +30

This will give you all files in the system that have been
modified over 30 days ago (i.e., 31+).

If you just want to look in the _current_directory_:  
  find . -maxdepth 1 -mtime +30

If you want to look at a particular file:  
  find /home/myfile -maxdepth 0 -mtime +30

If the file is listed, it was last modified 31+ days ago.

> How is that type of thing done in shell scripts.

Here's an example script that takes a list of files and moves
the files under /home/old (full path and attributes
preserved) if they are older than 30 days.

  fold30 file [file...]


1:  [ "$1" == "" ] && exit 1
2:  mylist="$*"
3:  for myfile in ${mylist}; do
4:    if [ -f "${myfile}" ]; then
5:      if [ "`find ${myfile} -mtime +30`" != "" ]; then
6:        echo ${myfile} | cpio -pmdvu /home/old/${myfile}
7:        rm -f ${myfile}
8:      fi
9:    fi
A:  done

The main conditional on line 5 is what does the job.  If the
result of the find command is not an empty string, then the
name was returned and it is older than 30 days.  Now move it
to the same path under /home/old (using cpio) and remove the

NOTE:  It will _not_ work if spaces are used in the paths,
that's something I've yet to see work correctly (I can never
get the "IFS" variable set to work proper in the loop) in
bash, so I professionally use tcsh instead.  Bash does not
seem to work with quotes in a loop like tcsh does, and the
Advanced Bash Scripting Guide (ABSG) is just _dead_wrong_ on
using quotes for most bash releases (although it works fine
across all tcsh versions I've used).

Bryan J. Smith                | Sent from Yahoo Mail
mailto:b.j.smith at ieee.org     |  (please excuse any
http://thebs413.blogspot.com/ |   missing headers)

More information about the CentOS mailing list