Tweaking Command Not Found

Most of the time in ubuntu, when we come across the message like : The program 'program_name' is currently not installed. You can install it by typing: sudo apt-get install program_name

We would end-up doing "sudo apt-get install program_name" and installing it.

This repeats so why not automate the same? Solving this question, I had to do the below :

Bash shell has a hook called command_not_found_handle

Most of the time in ubuntu, when we come across the message like : The program 'program_name' is currently not installed. You can install it by typing: sudo apt-get install program_name

We would end-up doing "sudo apt-get install program_name" and installing it.

This repeats so why not automate the same? Solving this question, I had to do the below :

Bash shell has a hook called command_not_found_handle

command_not_found_handle () 
{ 
    if [ -x /usr/lib/command-not-found ]; then
        /usr/bin/python /usr/lib/command-not-found -- $1;
        return $?;
    else
        if [ -x /usr/share/command-not-found ]; then
            /usr/bin/python /usr/share/command-not-found -- $1;
            return $?;
        else
            return 127;
        fi;
    fi
}

The above handler is basically invoking "/usr/lib/command-not-found", which makes use of the lib "./python2.6/dist-packages/CommandNotFound/CommandNotFound.py"

The crux of this lib is too check if there is a key for the given command in the db present at "/usr/share/command-not-found" and return suitable message.

Making a small hack, as below can achieve automatic package installation, if not already installed :

import subprocess
def check_install(command):
    cnf = CommandNotFound("/usr/share/command-not-found")

    result = set()
    for db in cnf.programs:
        result.update([(pkg,db.component) for pkg in db.lookup(command)])
    
    package = list(result)
    if(len(package) > 0 ):
            if subprocess.Popen("sudo apt-get -y install "+package[0][0],shell=True).wait() == 0:
            print "\n"
            print "Installation done !\n"
    
        else:
            print "\n"
            print " [>] Failed to install\n"

Now a simple invocation like :

check_install('sl')

would install the package 'sl'

Alternative easier hack! :

If you are from bash school, the hack is very simple :

check_install () 
{ 
    type -P $@ || sudo apt-get install $@
}

Place that in your ~/.bashrc and source ~/.bashrc and then you can do

check_install sl

Hack and let hack!

Share this