Tkinte-r Tkinte-r - 5 months ago 8
Linux Question

command_not_found_handler does not with with slashes

I have a problem with

"/"
sign in bash shell (version 4.3 in Ubuntu 16). I have a function:

command_not_found_handler() {
if [[ "$1" =~ any$ ]]; then
echo "$1"
fi
}


This function should write back the contents of any command written in the terminal when this command ends with
any
.

This works well, except in the situation when I write something with a
/
, such as
whatever/any
. In that event, I receive an error akin to the following:

bash: no such file or directory: whatever/any


Any attempts to escape this
/
in the function have no effect (for instance
if [[ "$1" =~ /any$ ]]; then
or
if [[ "$1" =~ \/any$ ]]; then
).

What can I do to make it work with
/
sign?

Answer

command_not_found_handle (no trailing r) is only invoked after doing a search through the PATH for a given command.

No such search occurs when the user is passing an explicit path to a command, which is how anything containing a / is interpreted.


To quote the relevant documentation, with emphasis added:

  1. If the name is neither a shell function nor a builtin, and contains no slashes, Bash searches each element of $PATH for a directory containing an executable file by that name. Bash uses a hash table to remember the full pathnames of executable files to avoid multiple PATH searches (see the description of hash in Bourne Shell Builtins). 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.

The entire paragraph of documentation is relevant only in the set of conditions set out at the beginning: A command must not be a shell function, must not be a builtin, and must not contain slashes.

Comments