44

I know that the command to update the repository lists is:

apt-get update

How to check if it has been executed today or in the last 24 hours?

I do not know if I should check some file timestamp. Or issue another apt command. Or use dpkg utility.

Could not find something useful at man pages.

galoget
  • 2,963
cavila
  • 563

13 Answers13

76

Check the time stamp of /var/lib/apt/periodic/update-success-stamp.

$ ls -l /var/lib/apt/periodic/update-success-stamp
-rw-r--r-- 1 root root 0 Jan 25 01:41 /var/lib/apt/periodic/update-success-stamp

Here the time is Jan 25 01:41 when apt-get last executed. To get the time only, use the following command in terminal,

$ ls -l /var/lib/apt/periodic/update-success-stamp | awk '{print $6" "$7" "$8}'
Jan 25 01:41

It is the best place to check the last update time. If you found /var/lib/apt/periodic/ to be empty you can try,

ls -l /var/log/apt/history.log

Update

It is found that due to some reasons above files update-success-stamp or history.log remain unavailable in some systems. There is a new proposal from derobert to look into the file /var/cache/apt/pkgcache.bin.

pkgcache.bin is Apt's memory mapped package cache location. It get renewed after each update. So it is the perfect candidate to know the last time when apt was updated.

One can use the following command to know the exact time,

ls -l /var/cache/apt/pkgcache.bin | cut -d' ' -f6,7,8

or

stat /var/cache/apt/pkgcache.bin
sourav c.
  • 44,715
  • my /var/lib/apt/periodic/ directory is empty – virtualxtc Jan 25 '14 at 08:08
  • My directory is also empty. Debian 7.3 wheezy. – cavila Jan 25 '14 at 11:53
  • Mine history file does not log apt update commands. So I could not find a line where to extract the timestamp. I could find an apt-get upgrade line only. – cavila Jan 25 '14 at 12:24
  • 8
    A better backup location would be /var/cache/apt/pkgcache.bin. Also, please don't parse the output of ls; use stat instead. Keep in mind that ls output depends on locale, depends on age of file, etc. (Also, I think you only get the first file you suggest if you have update-notifier-common installed) – derobert Mar 12 '14 at 16:12
  • @souravc ping on updating the answer—or would you like me to write up my own answer instead? – derobert Mar 19 '14 at 16:05
  • @derobert very sorry I completely forgot. I am updating your addition. You are always welcome to write your own answer. – sourav c. Mar 19 '14 at 16:54
  • Checking pkgcache.bin is the only reliable way to see if the 'update' command was run. Update won't log anything into history but it will regenerate the cache. – Ryaner May 01 '14 at 21:41
  • 2
    It seems /var/cache/apt/pkgcache.bin is also touched on package installation, so it's not a reliable way to check for the last apt-get update run. – GnP Dec 02 '16 at 20:18
  • As this answer points out, if you want to compare it programmatically in a shell script, you'll probably want to use stat with -c %Y for seconds since the epoch. – ssokolow Feb 22 '17 at 05:06
  • 4
    ...and I just discovered that a Debian 8 system where apt-get clean has been run recently will have no /var/cache/apt/pkgcache.bin. I'm going to try using the mtime from /var/lib/apt/lists instead, since that seems to be the raw, non-cached data which apt-get update actually manipulates. – ssokolow Feb 22 '17 at 10:12
  • Installing update-notifier-common on 16.04 provided /etc/apt/apt.conf.d/15update-stamp which contains the config to touch /var/lib/apt/periodic/update-success-stamp after successful update. Running apt-get update after installing update-notifier-common does indeed create the update-success-stamp file. – mattpr Feb 26 '19 at 12:37
20

You can check your command history in terminal :

history | grep 'apt update'

To check it by time :

HISTTIMEFORMAT="%d/%m/%y %T " history | grep '[a]pt update'

(The [a] part of the regular expression only matches the letter a but has the effect to not match itself when grepping in the history.)

Terminal history with timestamp

Lorenz Keel
  • 8,905
nux
  • 38,017
  • 35
  • 118
  • 131
  • 2
    It is history | grep 'apt-get update' :) – Lucio Jan 24 '14 at 19:47
  • try the updated answer and enjoy it my friend – nux Jan 24 '14 at 19:51
  • @Lucio It will not show the time of execution of a command. It just puts a timestamp to the commands. See all other commands. You can see all have same time. Is it not so? – sourav c. Jan 24 '14 at 19:56
  • @souravc No it will show each command by time excuted – nux Jan 24 '14 at 19:59
  • @nux have you checked by yourself, plz try HISTTIMEFORMAT="%d/%m/%y %T" && history | head. It puts smae time for all the commands that was executed earlier of using HISTTIMEFORMAT="%d/%m/%y %T" – sourav c. Jan 24 '14 at 20:05
  • check the picture man – nux Jan 24 '14 at 20:10
  • So should complemnt it with cut to enable a time expression comparison? – cavila Jan 25 '14 at 11:58
  • 7
    @souravc is right. This won't work on its own. If the HISTTIMEFORMAT is not set in .bashrc then this command will only have correct timestamps for the commands which were actually executed from the current shell session. For all the other commands which is not from the current session the timestamp will only show the modification timestamp of the ~/.bash_history file. It can't show the timestamps for commands from other sessions as those timestamps are not saved in the ~/.bash_history file. It can show timestamps for the current session because those stamps are still in the memory. – falconer Jan 25 '14 at 12:25
  • 11
    This does not always work. E.g. when some other user ran apt or when your .bash_history has been trimmed. – OrangeTux Jan 26 '14 at 20:11
  • 12
    This is a terribly wrong answer. It doesn't account for unattended upgrades, plus if you're someone like me who always has 4-5 terminals open, the history only gets saved when they exit (by default), so you would have to check all of them. – hackel May 16 '17 at 17:26
  • 3
    Echoing what everyone has already said, that won't work if apt has been updated by a script, if you're not looking at the right history, if the history has been trimmed, or if another user has done the update. That's really not reliable enough to solve the general case. – zneak Sep 25 '17 at 18:35
7

I use /var/cache/apt to determine if I need to run apt-get update. By default, if the difference between the current time and cache time of /var/cache/apt is less than 24 hr, I don't need to run apt-get update. The default update interval can be overridden by passing a number to function runAptGetUpdate()

function trimString()
{
    local -r string="${1}"

    sed -e 's/^ *//g' -e 's/ *$//g' <<< "${string}"
}

function isEmptyString()
{
    local -r string="${1}"

    if [[ "$(trimString "${string}")" = '' ]]
    then
        echo 'true'
    else
        echo 'false'
    fi
}

function info()
{
    local -r message="${1}"

    echo -e "\033[1;36m${message}\033[0m" 2>&1
}

function getLastAptGetUpdate()
{
    local aptDate="$(stat -c %Y '/var/cache/apt')"
    local nowDate="$(date +'%s')"

    echo $((nowDate - aptDate))
}

function runAptGetUpdate()
{
    local updateInterval="${1}"

    local lastAptGetUpdate="$(getLastAptGetUpdate)"

    if [[ "$(isEmptyString "${updateInterval}")" = 'true' ]]
    then
        # Default To 24 hours
        updateInterval="$((24 * 60 * 60))"
    fi

    if [[ "${lastAptGetUpdate}" -gt "${updateInterval}" ]]
    then
        info "apt-get update"
        apt-get update -m
    else
        local lastUpdate="$(date -u -d @"${lastAptGetUpdate}" +'%-Hh %-Mm %-Ss')"

        info "\nSkip apt-get update because its last run was '${lastUpdate}' ago"
    fi
}

Sample Output:

<root@ubuntu><~/ubuntu-cookbooks/libraries>
# runAptGetUpdate 

Skip apt-get update because its last run was '0h 37m 43s' ago

I extracted these functions from my personal github: https://github.com/gdbtek/ubuntu-cookbooks/blob/master/libraries/util.bash

5

Combining @ssokolow's last comment with the answer from here, this command will run apt-get update if it hasn't run in the last 7 days:

[ -z "$(find -H /var/lib/apt/lists -maxdepth 0 -mtime -7)" ] && sudo apt-get update

Explanation:

  • -mtime -7 finds files that have a change time in the last 7 days. You can use -mmin if you care about shorter times.
  • -maxdepth 0 ensures find won't go into the contents of the directory.
  • -H dereferences /var/lib/apt/lists if it's a soft link
  • If for some reason find fails, then the command would run. This seems to me like the safe default. If you want to flip the default, use -n in the test and -mtime +7 in the find command.
itsadok
  • 2,904
4

In case anyone is interested, this is the way Ansible does it:

APT_UPDATE_SUCCESS_STAMP_PATH = "/var/lib/apt/periodic/update-success-stamp"
APT_LISTS_PATH = "/var/lib/apt/lists"

[...]

def get_cache_mtime(): """Return mtime of a valid apt cache file. Stat the apt cache file and if no cache file is found return 0 :returns: int """ cache_time = 0 if os.path.exists(APT_UPDATE_SUCCESS_STAMP_PATH): cache_time = os.stat(APT_UPDATE_SUCCESS_STAMP_PATH).st_mtime elif os.path.exists(APT_LISTS_PATH): cache_time = os.stat(APT_LISTS_PATH).st_mtime return cache_time

Per Lundberg
  • 161
  • 7
3
LAST_UPDATED=$( stat --format="%X" /var/cache/apt/pkgcache.bin )
UNIX_TIME=$( date +%s )
TIME_DIFF=$(( UNIX_TIME - LAST_UPDATED ))

if [[ "${TIME_DIFF}" -gt 43200 ]]
then
  # It's been 12 hours since apt-get update was ran.
fi
  • You might just use: [ "$(( $(date +%s) - $(stat -c %Y /var/cache/apt/pkgcache.bin) ))" -gt 43200 ] && echo Time to go! – Suuuehgi Jun 10 '20 at 14:38
2

You can use this command to show last time it was accessed ie. running apt-get update also last time it was actually updated:

stat  /var/cache/apt/ | grep -i -e access -e modify

Note if the times are different there may not have been an update available. Since I have my updates and upgrades running by crontab at specific times I can tell if my updates ran or not.

galoget
  • 2,963
SCBB
  • 61
1

For apt specifically, I recommend this one-liner by @itsadok:

[ -z "$(find -H /var/lib/apt/lists -maxdepth 0 -mtime -7)" ] && sudo apt-get update

However If you want a more portable "update package manager at least every x days" semantics, you can simply touch a temp file when you update.

For example:

APT_UPDATED="/tmp/apt-update-tstamp"

Delete temp file created >1 day ago

find "$APT_UPDATED" -mtime +1 -exec rm {} ; 2>/dev/null

Update apt if needed

if [ ! -f "$APT_UPDATED" ]; then if apt-get update; then touch "$APT_UPDATED" fi fi

This should work in most scenarios since:

  • More updates wont hurt you (except time)
  • Doesn't rely on any apt internals (could expand to pkg, yum, etc)
galoget
  • 2,963
jchook
  • 216
1

You may also interested about the file:

/var/log/apt/term.log

Open it with less or cat as root.

  • This is a sensible place to check for logs of actions apt has performed on the package database, but afaik the poster wants to know about apt-get update, and that is obviously not logged. – Faheem Mitha Mar 12 '14 at 16:00
0

This command will work:

stat -c %y /var/lib/apt/periodic/update-success-stamp
logbasex
  • 349
0

In Ubuntu 21.10 You can grep the history.log like this:

grep -i 'Start-Date' /var/log/apt/history.log | tail -n1
Start-Date: 2022-03-07  11:09:14

This command will return the very last date of the apt update command.

0

The last-modified timestamp of /var/lib/apt/periodic/update-success-stamp is used to indicate the last time apt-get update was successfully run.

So to check if it's been more than 24 hours since we last ran apt-get update, use the following in Bash:

last_update=`stat -c %Y /var/lib/apt/periodic/update-success-stamp`
if [ $((`date +%s`-$last_update)) -gt $((24*60*60)) ]; then
  ...
fi

Explanation:

  • stat -c %Y /var/lib/apt/periodic/update-success-stamp gets the mtime timestamp (in seconds since Epoch) of the file.
  • date +%s gets the current time (in seconds since Epoch).
  • $((`date +%s`-$last_update)) calculates the difference, that is the number of seconds since the last successful apt-get update.
  • [ ... -gt $((24*60*60)) ] checks if this number is greater than the number of seconds in a day.
Jo Liss
  • 265
0

I just posted an answer to this question on following topic

Where can I look up my update history?

The answer may be less appropriate for this topic, as it specifically looks for "apt-get upgrade". Here's sample output.

xenial% 9: ./linuxpatchdate 
2016-07-19 54
2017-02-24 363
2017-03-08 7
2017-03-09 2

See the other topic for source code and more explanation.

JsinJ
  • 41
  • It looked to me like your code looked for upgrade, not update. For example, I just ran "apt-get update" (the subject of this question) on my Ubuntu 16.04 and not one iota of change appears in /var/log/apt, implying that scanning anything in that directory will be of no use in answer this particular question. – Ron Burk May 01 '17 at 20:56
  • 1
    You're totally right. Thanks for pointing that out. I've changed my answer to reflect that. We were looking for the last date updates were applied to the machine, rather than updates being just downloaded. – JsinJ May 04 '17 at 04:40