How to remove/install a package that is not fully installed?

For advanced users, use at your own risks.

According to the following error message :

subprocess installed post-installation script returned error exit status 127

You may want to edit /var/lib/dpkg/info/[package_name].postinst and comment everything (or better yet, try to understand it and identify the issue), then try apt-get again.

Note that though in this particular question the message concerns "post-installation", it could have mentioned e.g. "pre-removal" or "post-removal" instead (in which cases the extension of the file to be edited would have been .prerm or .postrm).


Other than those which you have already posted, there are few other commands which can be helpful.

  • Autoclean clears out the local repository of retrieved package files.

    sudo apt-get autoclean
    
  • Force installation/removal of packages. ☠Use with caution

    sudo apt-get --force-yes install <pkgname>
    

    and

    sudo apt-get --force-yes remove <pkgname>
    

Also as always, you can use dpkg to install, remove and purge packages.

  • Install

    sudo dpkg -i <pkgname>
    
  • Remove

    sudo dpkg -r <pkgname>
    
  • Purge

    sudo dpkg -P <pkgname>
    

So, after more googling and really carefully reading through the error messages again it seems that dpkg needed to be reinstalled.

sudo apt-get install --reinstall dpkg

What tipped off that this was the problem (if anyone searches and sees this) is that update-alternatives: not found was in the error message. As soon as dpkg was reinstalled, the other packages proceeded to install normally automatically.