Automatically update locate db on-demand

Oct 07, '11 07:30:00AM

Contributed by: Frankus

This hint provides a method to automatically insure that the locate db is not too old (but only) whenever you use the locate command (in Terminal or a script).

The hint:

Using your favorite text editor add the following line to the file called ~/.bash_profile. It's inside your Home directory as indicated but hidden. If it doesn't already exist you can create a new text file and save it to that path and name.
alias locate='if [ $((`date +%s`-`eval $(stat -s /var/db/locate.database); echo $st_mtime`)) -gt 3600 ]; then echo "locate: db is too old!">/dev/stderr; sudo /usr/libexec/locate.updatedb; fi; locate -i'

[crarko adds: Note that in creating the command alias you slightly change the meaning of the locate command; you can use a different alias if you want to keep both ways around and update manually. You lose some of the value of the hint if you do that.]

Comments (5)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20111007011922833