Both zsh
and bash
have hook functions that you can define to handle cases where a command is not found. It's called command_not_found_handle
in bash
and command_not_found_handler
in zsh
(inspired by bash
's but with the typo/misnomer fixed).
Note however that they run in a child process (not to mention that the command could be not-found by a subshell), so cannot make changes to your shell environment.
You could do:
zsh
command_not_found_handler() {
{
if (( ! IN_CNFH++)) && load_lib "$1"; then
"$@"
else
print -ru2 -- "$functrace[1]: command not found: $1"
return 127
fi
} always {
(( IN_CNFH-- ))
}
}
The IN_CNFH
parts to avoid infinite recursion if the command still can't be found after load_lib
succeeded.
If you already have a command_not_found_handler
(some systems provide one in their zsh default configuration to suggest names of packages to install when a command is not found), you could insert that before it with something like:
functions[command_not_found_handler]='
{
if (( ! IN_CNFH++)) && load_lib "$1"; then
"$@"
return
fi
} always {
(( IN_CNFH-- ))
}
'$functions[command_not_found_handler]
bash
The equivalent in bash would look like:
command_not_found_handle() {
local ret
if (( ! IN_CNFH++)) && load_lib "$1"; then
"$@"
ret=$?
else
printf >&2 '%s\n' "$BASH_ARGV0: $1: command not found: $1"
ret=127
fi
(( IN_CNFH-- ))
return "$ret"
}
Or the incremental variant in case there's already a command_not_found_handle
:
eval 'command_not_found_handle() {
local ret
if (( ! IN_CNFH++)) && load_lib "$1"; then
"$@"
ret=$?
(( IN_CNFH-- ))
return "$ret"
fi
(( IN_CNFH-- ))
'"$(typeset -f command_not_found_handle | tail -n +2)"'
}'
command_not_found_handle
and zshcommand_not_found_handler
- some discussion here Command not found message