57

How do I write a script to determine if a file is older than 30 minutes in /bin/sh?

Unfortunately does not the stat command exist in the system. It is an old Unix system, http://en.wikipedia.org/wiki/Interactive_Unix

Perl is unfortunately not installed on the system and the customer does not want to install it, and nothing else either.

8
  • Interactive Unix, wow. If you're on a really non-standard and out of date Unix rather than struggling with whatever wacky versions of shell utilities they have your best bet might be to use Perl. It should compile (it has provisions for Interactive Unix, but you might have to use an older version as I doubt anyone's done it in a while) and it might already be installed. Then its just use File::stat; print "Older" if (time - stat($file)->mtime) > 60*30;
    – Schwern
    Jan 5, 2010 at 13:36
  • 1
    perl is unfortunately not installed on the system and the customer does not want to install it.
    – magol
    Jan 5, 2010 at 13:44
  • @magol Time to convince the customer to install some updated software methinks. Show them how many hours you're wasting by struggling with out of date software, translate it into the extra $money$ you have to charge them for doing even a simple task. Then ask for updates.
    – Schwern
    Jan 5, 2010 at 21:47
  • 1
    @magol In that case, rather than upgrading the existing software install the necessary software outside of PATH. Stick it into /usr/local/whatever outside the normal PATH and reference it directly, or even just in your home directory. That has no risk and low effort.
    – Schwern
    Jan 6, 2010 at 16:35
  • 1
    I did solve it by write a C program that my script use.
    – magol
    Jan 22, 2011 at 13:19

13 Answers 13

83

Here's one way using find.

if test "`find file -mmin +30`"

The find command must be quoted in case the file in question contains spaces or special characters.

8
  • 1
    find does not have -mmin in Interactive Unix :-(
    – magol
    Jan 5, 2010 at 13:23
  • something like test "`find "hej med dig" -mmin +30 | head -1`" to support whitespace in filename Jan 5, 2012 at 12:30
  • 6
    Unfortunately, I don't think it will work reliably. If find does return a file name and that doesn't form an acceptable argument to the test builtin, shell will declare it to be an error. The only reason the solution provided by @Schwern worked is because find returned an empty string which test evaluates to a non-zero exit status. A better solution, in my opinion would be to check if find has returned an empty string or not. Find does not have a non-zero exit status if it doesn't locate a file. Otherwise, one could have perhaps used if find file -min +30.
    – gkb0986
    Sep 14, 2013 at 6:42
  • 1
    @Schwern here you go. Sorry for the delay. cd test_dir; touch my\ file\ with\ spaces; test $(find . -type f). The output on bash 4.2 is -bash: test: <filename> unary operator expected. The problem, as you might have guessed, is quoting. If you quote the command substitution, it works fine.
    – gkb0986
    Sep 18, 2013 at 7:36
  • 1
    @gkb0986 Thanks, I made a mistake setting the file time when I was doing my check.
    – Schwern
    Sep 24, 2013 at 7:37
37

The following gives you the file age in seconds:

echo $(( `date +%s` - `stat -L --format %Y $filename` ))

which means this should give a true/false value (1/0) for files older than 30 minutes:

echo $(( (`date +%s` - `stat -L --format %Y $filename`) > (30*60) ))

30*60 -- 60 seconds in a minute, don't precalculate, let the CPU do the work for you!

9
  • 20
    Readability & maintainability. Which is much, much more import than speed.
    – slebetman
    May 1, 2013 at 21:57
  • 2
    For a single command like this yes, but in high number environments it's a bad habit with a costly disadvantage: waste of resources. If you need a calculator to know how long 7200 seconds is you are making yourself dumb like using a Tom-Tom does.
    – Leo
    May 13, 2013 at 13:52
  • 11
    @Leo if calculating a product of two numbers is awful waste of resources for your application, you'd better using compilable language like C for your problem, not scripting one like sh.
    – Ruslan
    May 13, 2013 at 19:56
  • 2
    @Leo: In a high number of environments it is much more costly for code to contain magic numbers than it is to waste CPU time. Only in a small number of cases is extreme micro optimization warranted. But even in those cases most experienced programmers would tell you the first rule of optimization.
    – slebetman
    May 14, 2013 at 1:47
  • 6
    You are wasting time and resources here discussing that micro minor issue. Write 30*60 or 1800, whatever you like better. No programmer will have a real problem understanding either. Really. And only in very very rare cases will any wasted resource because of a 30*60 will have any measurable effect. Keep your feet on the ground.
    – Alfe
    Oct 6, 2014 at 10:24
25

If you're writing a sh script, the most useful way is to use test with the already mentioned stat trick:

if [ `stat --format=%Y $file` -le $(( `date +%s` - 1800 )) ]; then 
    do stuff with your 30-minutes-old $file
fi

Note that [ is a symbolic link (or otherwise equivalent) to test; see man test, but keep in mind that test and [ are also bash builtins and thus can have slightly different behavior. (Also note the [[ bash compound command).

1
  • 1
    Unfortunately does 'stat' not exist in the system :-( It is an old Unix system
    – magol
    Jan 5, 2010 at 13:08
12

Ok, no stat and a crippled find. Here's your alternatives:

Compile the GNU coreutils to get a decent find (and a lot of other handy commands). You might already have it as gfind.

Maybe you can use date to get the file modification time if -r works?

(`date +%s` - `date -r $file +%s`) > (30*60)

Alternatively, use the -nt comparision to choose which file is newer, trouble is making a file with a mod time 30 minutes in the past. touch can usually do that, but all bets are off as to what's available.

touch -d '30 minutes ago' 30_minutes_ago
if [ your_file -ot 30_minutes_ago ]; then
    ...do stuff...
fi

And finally, see if Perl is available rather than struggling with who knows what versions of shell utilities.

use File::stat;
print "Yes" if (time - stat("yourfile")->mtime) > 60*30;
9
  • bourne does not have -nt , -ot tests, does it?
    – ghostdog74
    Jan 5, 2010 at 14:05
  • "date -r" does not work. "touch -d" does not work. But I can set time if I give exact time. But How do I get the time 30 minutes ago? I can't use Perl
    – magol
    Jan 5, 2010 at 17:07
  • @magol date -d '30 minutes ago' +%s will give you the time 30 minutes ago.
    – Schwern
    Jan 5, 2010 at 21:45
  • @ghostdog74 I guess I'm looking at bash not sh. I haven't seen a real Bourne Shell in years.
    – Schwern
    Jan 6, 2010 at 16:33
  • 1
    date -r works great in OpenWrt Busybox, which doesn't have stat or a find with mtime.
    – Kris Braun
    Nov 16, 2016 at 3:22
5

For those like myself, who don't like back ticks, based on answer by @slebetman:

echo $(( $(date +%s) - $(stat -L --format %Y $filename) > (30*60) ))
4

Here's my variation on find:

if [ `find cache/nodes.csv -mmin +10 | egrep '.*'` ]

Find always returns status code 0 unless it fails; however, egrep returns 1 is no match is found`. So this combination passes if that file is older than 10 minutes.

Try it:

touch /tmp/foo; sleep 61; 
find /tmp/foo -mmin +1  | egrep '.*'; echo $?
find /tmp/foo -mmin +10 | egrep '.*'; echo $?

Should print 0 and then 1 after the file's path.

My function using this:

##  Usage: if isFileOlderThanMinutes "$NODES_FILE_RAW" $NODES_INFO_EXPIRY; then ...
function isFileOlderThanMinutes {
  if [ "" == "$1" ] ; then serr "isFileOlderThanMinutes() usage: isFileOlderThanMinutes <file> <minutes>"; exit; fi
  if [ "" == "$2" ] ; then serr "isFileOlderThanMinutes() usage: isFileOlderThanMinutes <file> <minutes>"; exit; fi
  ##  Does not exist -> "older"
  if [ ! -f "$1" ] ; then return 0; fi
  ##  The file older than $2 is found...
  find "$1" -mmin +$2 | egrep '.*'  > /dev/null 2>&1;
  if [ $? == 0 ] ; then return 0; fi  ## So it is older.
  return 1;  ## Else it not older.
}
3

You can do this by comparing to a reference file that you've created with a timestamp of thirty minutes ago.

First create your comparison file by entering

touch -t YYYYMMDDhhmm.ss /tmp/thirty_minutes_ago

replacing the timestamp with the value thirty minutes ago. You could automate this step with a trivial one liner in Perl.

Then use find's newer operator to match files that are older by negating the search operator

find . \! -newer /tmp/thirty_minutes_ago -print
5
  • newer works. But what do \! mean? How do I get the time 30 minutes ago in \bin\sh?
    – magol
    Jan 5, 2010 at 17:05
  • @magol, just subtract it, e.g. I'm writing this at 17:22 on 5/1/2010 so the command for the "thirty minutes ago" file is touch -t 201001051652.00 /tmp/thirty_minutes_ago. Or you could use a Perl one liner to calculate it. The "\!" means not for the find command so "not newer" is older. HTH
    – Rob Wells
    Jan 5, 2010 at 17:23
  • Does Interactive Unix happen to have Tcl? It has good date handling routines.
    – mpez0
    Jan 8, 2010 at 14:59
  • Eliminating the Perl: time_now=date +%s time_then=expr $time_now - 1800 time_file=date -r <filename> +%s if $time_then -gt $time_file; then echo "<filename> is more than 30 minutes old"; else echo "<filename> is less than 30 minutes old"; fi (untested, but should be close enough. Insert returns; I can't format the comment)
    – mpez0
    Jan 8, 2010 at 15:03
  • \! is just escaping the ! so that it is passed through to the find command rather than the shell expanding it,
    – Rob Wells
    Mar 11, 2016 at 17:40
3

Difference in seconds between current time and last modification time of myfile.txt:

echo $(($(date +%s)-$(stat -c "%Y" myfile.txt)))

you can also use %X or %Z with the command stat -c to get the difference between last access or last status change, check for 0 return!

%X time of last access, seconds since Epoch
%Y time of last data modification, seconds since Epoch
%Z time of last status change, seconds since Epoch

The test:

if [ $(($(date +%s)-$(stat -c "%Y" myfile.txt))) -lt 600 ] ; then echo younger than 600 sec ; else echo older than 600 sec ; fi
2

What do you mean by older than 30 minutes: modified more than 30 minutes ago, or created more than 30 minutes ago? Hopefully it's the former, as the answers so far are correct for that interpretation. In the latter case, you have problems since unix file systems do not track the creation time of a file. (The ctime file attribute records when the inode contents last changed, ie, something like chmod or chown happened).

If you really need to know if file was created more than 30 minutes ago, you'll either have to scan the relevant part of the file system repeatedly with something like find or use something platform-dependent like linux's inotify.

2
#!/usr/bin/ksh
## this script creates a new timer file every minute and renames all the previously created timer files and then executes whatever script you need which can now use the timer files to compare against with a find.  The script is designed to always be running on the server.  The first time the script is executed it will remove the timer files and it will take an hour to rebuild them (assuming you want 60 minutes of timer files)

set -x

# if the server is rebooted for any reason or this scripts stops we must rebuild the timer files from scratch
find /yourpath/timer -type f -exec rm {} \;

while [ 1 ]
do
COUNTER=60
COUNTER2=60
cd /yourpath/timer
while [ COUNTER -gt 1 ]
do
  COUNTER2=`expr $COUNTER - 1`
  echo COUNTER=$COUNTER
  echo COUNTER2=$COUNTER2
  if [  -f timer-minutes-$COUNTER2 ]
    then
       mv timer-minutes-$COUNTER2 timer-minutes-$COUNTER
       COUNTER=`expr $COUNTER - 1`
  else
     touch timer-minutes-$COUNTER2
  fi
done

touch timer-minutes-1
sleep 60

#this will check to see if the files have been fully updated after a server restart
COUNT=`find . ! -newer timer-minutes-30 -type f | wc -l | awk '{print $1}'`
if [ $COUNT -eq 1  ]
   then
     # execute whatever scripts at this point
fi

done
2

You can use the find command.
For example, to search for files in current dir that are older than 30 min:

find . -type f -mmin +30 

You can read up about the find command HERE

2
  • 1
    Thank you for your excellent response to my old question. Unfortunately, someone else has given the same answer before you. stackoverflow.com/questions/2005021/…
    – magol
    Oct 15, 2017 at 20:51
  • 1
    First of all, you are welcome. ;) Secondly, i have seen the answer, just wanted to add a little more detail and literature to help you out even further. Cheers, Milos. Oct 16, 2017 at 6:57
1

Given the constraints of the system in question, and my inability to access anything akin to it, I'm uncertain whether this might work, however one possible solution that doesn't use perl or stat(1) might be to use awk:

At least in a modern GNU Awk, one can get a time that's "30 minutes ago" with the following:

awk 'END {print strftime("%Y%m%d%H%M.%S", systime()-1800)}' < /dev/null

One could then plug that in to touch to make a file that's marked as being 30 minutes old, and then use the -ot or -nt options of test (or [/]). Putting things together for a simple test case, one might try:

#!/bin/sh

touch -t "`awk 'END {print strftime("%Y%m%d%H%M.%S", systime()-1800)}' < /dev/null`" .30minutes

if [ ! -f testfile ]; then
        echo "please create testfile before testing."
elif [ testfile -nt .30minutes ]; then
        echo "testfile is newer than 30 minutes old"
else
        echo "testfile is 30 minutes old or older"
fi

This works for me on a modern Ubuntu machine. Whether it would work with the /bin/sh and touch and test of an Interactive Unix system, I leave as an exercise to those who have access to such a system.

0
if [[ "$(date --rfc-3339=ns -r /tmp/targetFile)" < "$(date --rfc-3339=ns --date '90 minutes ago')" ]] ; then echo "older"; fi
1
  • 2
    Welcome to Stack Overflow! Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. In particular, what is the significance of 90 minutes ago in this code? May 23, 2017 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.