Find and Delete File If It Is More Than One Hour Old in UNIX Shell

Q. How do I find out file last modification time using a shell script or command? How do I delete or take any other custom action for all files more than one hour old in /home/ftp/incoming/raw/ directory?

A. There are many ways (commands) to find out file modification time under UNIX / Linux operating system. You can try any one of the following command:

ADVERTISEMENTS

find command (with -cmin switch)

$ find /home/ftp/incoming/raw/ -maxdepth 1 -cmin +60 -name FileName
The -cmin option will print FileName’s status was last changed n minutes ago. This command will print all file names more than one hour old.

stat command (with -c switch)

To find time of last change as seconds since Epoch, enter:
$ stat -c %Z /path/to/file

date command (with -r switch)

To display the last modification time of FILE, enter:
$ date -r /path/to/file
I recommend using find command as it has -exec option to take action on all matching file such as move or delete files:
$ find /home/ftp/incoming/raw/ -maxdepth 1 -cmin +60 -name "*" -exec /bin/rm -f {} \;

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
3 comments… add one
  • Jeff Schroeder Apr 21, 2008 @ 13:57

    find … -exec is BAD!

    For every single result, it will fork off a copy of the command you exec. So if the above find command returns 500 files, rm will be forked 500 times.

    Instead of doing it the above way, try this:
    find /home/ftp/incoming/raw/ -maxdepth 1 -cmin +60 | xargs rm -rf

    The -name ‘*’ argument to find was redundant.

  • ojo Apr 26, 2008 @ 6:27

    Isn’t it better to use null character as a files separator (because of spaces in file/dir names)? like this:

    find /home/ftp/incoming/raw/ -print0 -maxdepth 1 -cmin +60 | xargs -0 rm -rf

  • Actually May 13, 2014 @ 7:09

    its very good that -exec forks off a new process. Some commands have an upper limit of how many arguments you can give it. No complaining.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.