From the Bash man page:
COMMAND EXECUTION
[…]
If the name is neither a shell function nor a builtin, and contains no slashes, bash searches each element of the PATH
for a directory containing an executable file by that name. Bash uses a hash table to remember the full pathnames of executable files (see hash
under SHELL BUILTIN COMMANDS below). A full search of the directories in PATH
is performed only if the command is not found in the hash table. If the search is unsuccessful, the shell searches for a defined shell function named command_not_found_handle
. If that function exists, it is invoked with the original command and the original command's arguments as its arguments, and the function's exit status becomes the exit status of the shell. If that function is not defined, the shell prints an error message and returns an exit status of 127.
Let's try this out:
$ foobar
bash: foobar: command not found
$ function command_not_found_handle { echo "I'm so sorry, what is '$1'?"; }
$ foobar
I'm so sorry, what is 'foobar'?
Your shell initialization code might install a more useful command_not_found_handle
. You would typically find such code in the system-wide configuration in /etc/bash.bashrc
or a file sourced by it. Your distribution might install a handler there to invoke an external program that queries the distribution's package manager for the command or “similar” commands. For your Ubuntu, this would be implemented in the command-not-found
package.
The default configuration files shipped by distributions are usually kept very general so the function might check whether the command-not-found
binary is installed and, if so, call it or otherwise print a simple error message.
function command_not_found_handle {
if [ -x /usr/bin/command-not-found ]
then
/usr/bin/command-not-found "$1"
else
echo "$1: Command not found" >&2
return 127
fi
}
This way, the configuration file does not have to be changed if the command-not-found
package is installed or removed again later.
I don't know how that program for Ubuntu is implemented but typically, such a tool would have a list of all known commands and find the most similar one. It might then check whether that program is installed and, if not, check what package provides it and suggest installing that.
Searching for “similar text” is usually done by computing the edit distance between two strings. Taking into account how likely mistyping a given letter is, given the current keyboard layout, would be a very smart addition.