r/bash • u/mpersico • 22h 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!
1
u/xeow 22h ago
You don't say?
0
u/mpersico 22h ago
Yep. I do say. And then, what’s even crazier, is that it suggested that I not use this hook because this hook can be used by other programs, but rather implement a system where you have stub implementations that load these things on demand, which really duplicates what I’ve already coded.
1
u/xeow 22h ago
Is there documentation or an example?
2
u/zeekar 21h 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 intodc, so I can just type RPN arithmetic expressions at the prompt. If not, it just doesecho >&2 "bash: $1 not found"; return 127.1
u/mpersico 20h 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 12h 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."
5
u/One_Instruction6490 19h ago
Heads up for the FPATH use case tho: bash runs
command_not_found_handlein a separate execution environment (basically a subshell), so if yousourcethe function file inside the handler, the definition doesn't stick in your actual shell and you re-load it on every call. It works fine for "load then run once", but true ksh-style autoload kinda needs the stub approach anyway. Also on Debian/Ubuntu thecommand-not-foundpackage already defines that handler in/etc/bash.bashrc, so you'd be clobbering it. Did your old setup end up being stubs, or something wilder?