I am writing a bash script to install software and update Ubuntu 12.04. I would like the script to be able to check for apt-get errors especially during apt-get update so that I can include corrective commands or exit the script with a message. How can I have my bash script check for these types of errors?
Edit March 21st:
Thank you terdon for the providing just the information I needed! Here is the script I created with a combination of your suggestions to check for updates and recheck when errors occur and then report back. I will be adding this to a longer script that I am using to customize new Ubuntu installations.
#!/bin/bash
apt-get update
if [ $? != 0 ];
then
echo "That update didn't work out so well. Trying some fancy stuff..."
sleep 3
rm -rf /var/lib/apt/lists/* -vf
apt-get update -f || echo "The errors have overwhelmed us, bro." && exit
fi
echo "You are all updated now, bro!"
Best Answer
The simplest approach is to have your script continue only if
apt-get
exits correctly. For example:Alternatively, exit if any steps failed:
This would give the following output:
This is taking advantage of a basic feature of bash and most (if not all) shells:
&&
: continue only if the previous command succeeded (had an exit status of 0)||
: continue only if the previous command failed (had an exit status of not 0)It is the equivalent of writing something like this:
Note that if a package is already installed,
apt-get
will run successfully, and the exit status will be 0.