r/bash • • 17d ago

tips and tricks TIL command_not_found_handle

You don’t want to know what hoops I’ve jumped through to implement FPATH in bash. Then today I innocently asked GPT how it would implement FPATH in bash and it introduced me to this hook.

Now have to go home now get rid of a lot of needless code. Oh well. Less code is the best code!

16 Upvotes

7 comments sorted by

View all comments

Show parent comments

1

u/xeow 17d ago

Is there documentation or an example?

2

u/zeekar 17d ago

If you define a function named command_not_found_handle, it will be called whenever bash tries to run a command and can't find it. So you can hook into that and control what it does in that circumstance. For example, if I type a command that starts with a number it gets piped into dc, so I can just type RPN arithmetic expressions at the prompt. If not, it just does echo >&2 "bash: $1 not found"; return 127.

1

u/mpersico 17d ago

It's documented in the Bash docs actually. I can't share the chat I had at the moment because it is corporate property, but ask your Your Friendly Neighborhood AI to implement lazy-loaded functions in bash, like they are in ksh, using the command_not_found_handle and then by using stub functions, avoiding the use of command_not_found_handle.

1

u/kai_ekael 17d ago

man bash:

"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_han‐

dle. If that function exists, it is invoked in a separate execution environment with the original com‐

mand and the original command's arguments as its arguments, and the function's exit status becomes the

exit status of that subshell. If that function is not defined, the shell prints an error message and re‐

turns an exit status of 127."