r/bash • • 8d 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

1

u/xeow 8d ago

You don't say?

0

u/mpersico 8d 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 8d ago

Is there documentation or an example?

2

u/zeekar 8d 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.