UPDATE: It will now try to install /bin/program, /usr/bin/program, /sbin/program, or /usr/sbin/program.
This is totally automatic...
Say you type in g++ main.cpp
and you do not have g++ installed, it will ask if you want to install package g++, and if you answer yes, it will install it and then run g++ main.cpp
.
(This is a one-time setup... Do this and you are good to go)
- Install apt-file...
sudo apt-get install apt-file
- Update its cache...
sudo apt-file update
Edit ~/.bashrc and add this to it:
command_not_found_handle () {
ask () {
echo -ne "$1 (Y/n) ";
read -N1 YES_ANSWER;
echo "";
YES_ANSWER=`echo $YES_ANSWER | sed 's/Y/y/; s/N/n/;'`;
if [ "x$YES_ANSWER" == "xy" ]; then
unset YES_ANSWER;
return 0;
elif [ "x$YES_ANSWER" == "xn" ]; then
unset YES_ANSWER;
return 1;
elif [ "x$YES_ANSWER" == "x" ]; then
unset YES_ANSWER;
return 0;
else
ask_yes "$1";
unset YES_ANSWER;
return $?;
fi;
}
if [ "x$1" == "x" ]; then
echo "File name not provided.";
return 1;
fi;
echo "Command not found: $1";
echo "Searching for file in database...";
FILE="`apt-file search /bin/$1 | sed 's/: /_/'`";
if [ "x$FILE" != "x" ]; then
FILE="`apt-file search /usr/bin/$1 | sed 's/: /_/'`";
fi;
if [ "x$FILE" != "x" ]; then
FILE="`apt-file search /sbin/$1 | sed 's/: /_/'`";
fi;
if [ "x$FILE" != "x" ]; then
FILE="`apt-file search /usr/sbin/$1 | sed 's/: /_/'`";
fi;
if [ "x$FILE" != "x" ]; then
for f in "$FILE"; do
if ask "\nDo you want to install package `echo $f | sed 's/_.*$//'` which provides `echo $f | sed 's/^.*_//'`?"; then
sudo apt-get install `echo $f | sed 's/_.*$//'`;
"$@";
return $?;
fi;
done;
else
echo "Could not find file $1.";
return 1;
fi;
}
I am still testing this, but in the preliminary test it seems to work. Every now and then it would be good to run apt-file update
to refresh the list of available files.
To make the edited ~/.bashrc become effective, do one of the following:
log out and log back in again, or
run . ~/.bashrc
.