How can I use a list of packages to determine whether or not I need to do apt-get update on Ubuntu 20.10?

2k views Asked by At

I am writing a numerous shell scripts, which depends on specific packages.

For example one of my scripts depends on ca-certificates and wget. If I have not yet run apt-get -y update, then I get the following errors:

Package ca-certificates is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source.

E: Package 'ca-certificates' has no installation candidate
E: Unable to locate package wget


I want to avoid running apt-get -y update on every script. Basically, I want to create a shortcut function which will do the following two things:

  1. Run apt-get -y update only when necessary.
  2. Install only the packages which are not installed/latest.

Here is my current function so far:

function install-packages()
{
    apt-get -y update
    apt-get install -y --no-install-recommends $@
}

install-packages ca-certificates wget
1

There are 1 answers

0
Sudip Ghimire On

To check if package is installed or not do something like

dpkg -l | grep vlc | awk '{print $2}'

and to check if the package is available with apt and for apt-get search for similar option. It exist but I do not remember anyway all new distro use apt

apt list --upgradable | awk '{print $1}'

compare each row(package name) from above output to the package you are targeting in your script.

Your try to run apt update only when necessary is challenging. One thing is to run apt update when apt generate error which will solve the problem like you mentioned but as apt could have reported error with other things too so this method is so uneffective.

If all you trying to do is to prevent repeated execution of same package everytime you can create a file tracking the last time your program did update by

apt update -y && echo date > ~/.track

and then do update only when that time is greater than a certain period like 1 week for debian stable.

Edit: Some folks said you can do something like

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

where -mmin -60 check for apt package list cache for last 1 hour. Adjust that value and you are good to go unless user or something don't write that file manually. Things can go bad also when some disk freeing application removes cache.