Bash: How to Check if File is Older than 1 Hour


Often you may want to use Bash to check if a particular file is older than 1 hour.

You can use the following syntax to do so:

echo $(( (`date +%s` - `stat -L --format %Y athletes.csv`) > (1*60*60) ))

This particular example will check if the file named athletes.csv in the current directory is older than 1 hour and return one of the following as a result:

  • 0 if the file is not older than 1 hour
  • 1 if the file is older than 1 hour

Note that this syntax returns the age of the file in seconds:

echo $(( `date +%s` - `stat -L --format %Y athletes.csv`))

Thus, by checking if it is greater than (1*60*60) we are able to check if the file is older than 1 hour.

Note: Simply replace the 1 with n to check if the file is older than n hours.

The following example shows how to use this syntax in practice.

Example: How to Check if File is Older Than 1 Hour in Bash

Suppose that we would like to check if a file named athletes.csv in our current directory is older than 1 hour.

We can first use the ls command with the following syntax to view the file creation date and time:

ls -l athletes.csv

The following screenshot shows how to use this syntax in practice:

We can see that this particular file was created on August 15th and 8:26 AM.

This article is currently being written on August 15th at 9:20 AM.

We can use the following syntax to check if the athletes.csv file is older than 1 hour:

echo $(( (`date +%s` - `stat -L --format %Y athletes.csv`) > (1*60*60) ))

The following screenshot shows how to use this syntax in practice:

Bash check if file is older than 1 hour

This returns a value of 0, which tells us that the file is not older than 1 hour.

Feel free to replace athletes.csv with the name of your own file that you’d like to check.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Delete Files Older than X Hours
Bash: How to Find All Files that Were Created Today
Bash: How to Find Files that Have Been Changed in Last 24 Hours

Leave a Reply