0

I've written a bash script to install some packages on the first boot of my Ubuntu 16.04 VPS. The VPS platform that I'm using runs it during the server commissioning process. When it runs I'm getting this sort of error:

...
Reading package lists...
E: Could not get lock /var/lib/apt/lists/lock - open (11: Resource temporarily unavailable)
E: Unable to lock directory /var/lib/apt/lists/
...

So my question is: How do I sleep until it's okay go go ahead with the install?

I've done quite a bit of Googling to find a solid answer to this (I'm new to bash scripting), and have come across several proposed solutions, but there's lots of noise. Some answers are specific to certain provisioning systems, and other approaches seem a bit hacky.

My solution at the moment is just a sleep 30 at the top of my script which is definitely not a robust solution.

I tried putting together something like this but it doesn't seem to work:

while true
do
  sudo lsof /var/lib/apt/lists/lock &> /dev/null
  [ $? = 0 ] && break
  sleep 1
done

On my personal machine it sleeps forever because of an error (WARNING: can't stat() fuse.gvfsd-fuse...), and on the VPS, it doesn't seem to sleep at all.

Any ideas why that doesn't work, or ideas for a better approach?


By the way, if you're interested, the script I'm trying to run is simply:

#!/bin/sh
curl -sL https://deb.nodesource.com/setup_8.x | bash -
apt-get install -y nodejs

And the full output can be seen in this pastebin.

0

1 Answer 1

0

Put this in your script, then start your script with sudo.

#!/bin/sh

while [ -f /var/lib/apt/lists/lock
do
# The lock file is found, wait for it to be removed.
  sleep 3
done

# The lock file is not found, let's perform our actions.
curl -sL https://deb.nodesource.com/setup_8.x | bash -
apt-get install -y nodejs
3
  • Thanks! I'll be able to test this soon. This answer says that since Debian Wheezy the lock files always exist, so would the -f option of test work here? This answer uses fuser - would that be better?
    – user606179
    Oct 16, 2017 at 4:18
  • 1
    The instruction [ -f file ] is short version of the test command. You are right, I did not realize the file always exists. My answer will be stuch in the while-loop forever too. I found this post which looks very useful. askubuntu.com/questions/132059/…
    – user680858
    Oct 16, 2017 at 8:58
  • 1
    In follow up to my previous comment. I think using the aptdcon looks very reliable. Still, if you want to do test the lockfiles yourself, look at: askubuntu.com/questions/15433/…
    – user680858
    Oct 16, 2017 at 9:31