apt-get error kills my bash function
Question
I'm trying to write a simple function for my .bashrc, to simplify a common issue I have:
$ sudo apt-get install nltk
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package nltk
$ apt-cache search nltk
python-nltk - Python libraries for natural language processing
$ sudo apt-get install python-nltk
So I wrote this:
function sagi(){
sudo apt-get install $1 || apt-cache search $1
}
But no matter what I do, after the apt-get install
part runs and errors out because it can't find the package I asked for, the function exits completely. I even tried doing this:
function sagi(){
sudo apt-get install $1
echo $1
}
Again, nothing after the failed apt-get runs. Strangely enough, when I run:
$ sudo apt-get install nltk || apt-cache search nltk
(at the bash prompt) everything works as expected. What am I doing wrong?
Edit: The function is at the end of my .bashrc file, and is shown in its entirety above. I checked, and my .bashrc doesn't use set
anywhere. (I initially suspected that set -e
might be the culprit). No traps, either, and the error code from $? is 100.
Solution
It is not really a solution but an improvement suggestion.
function sagi() {
sudo apt-get -qq --dry-run install $1
if [ $? == 100 ]; then
sudo apt-cache search $1
else
sudo apt-get install $1
fi
}
This would get you a cleaner and more secure way to do what you want. At first it checks if that package is in the repositories by performing a dry run first. After that it checks whether the error code is 100 (failed due to package not found) and invoking a cache search if so else it just installs the package.