4

I'm on debian. I would like to execute an apt-get update (and maybe something else) only if the time since last update is bigger or smaller than a certain amount with a straight command, no cron tricks or similar.

Let's assume I know nothing about apt-get previous state, an update could have been never issued since the os installation, or triggered manually 2 mins ago, or issued automatically by unattended-upgrades service.

Eg.

if(time > 30 min) apt-get update
if(time > 2 days) something else

This question is similar to another I found in askubuntu but due the different setup in debian config I can't find a timestamp file informing me when the last update command took place.

6

The file /var/cache/apt/pkgcache.bin is regenerated each time apt-get update runs (and isn't regenerated otherwise).

For example, if you want to run apt-get update only if it hasn't been run in the past hour, you can use

#!/bin/sh
last_update=$(stat -c %Y /var/cache/apt/pkgcache.bin)
now=$(date +%s)
if [ $((now - last_update)) -gt 3600 ]; then
  apt-get update
fi

or

#!/bin/sh
if [ -z "$(find /var/cache/apt/pkgcache.bin -mmin -60)" ]; then
  apt-get update
fi

Note that if you run multiple copies of this script almost at the same time, they might all decide to run apt-get update. If that's a concern, use a lock (which is a wholly separate issue).

2
  • Please extend your answer with a full working code to take advantage of this info. What should to be done with this file? Get the creation (or the modified) date in seconds, do the actual time minus that dat in seconds and make a comparison? What if this file was never created? eg: debian plain installed from cd and never issued an update.. please cover this aspects in the answer, thanks :) – user3450548 Mar 20 '16 at 18:22
  • @user3450548 That's one way, though calling find is more direct. I've added code snippets to my answer. – Gilles 'SO- stop being evil' Mar 20 '16 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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