1

I am looking for a bash/zsh hook, that is invoked when a command is not found.

Say I run some arbitrary executable:

xyz foo --bar
  1. say that bash/zsh cannot find the executable.
  2. is there a way to handle "not found" and then load some libraries to the PATH dynamically after that?

something like this:

function xyz {
  if ! test -f xyz; then
     load_libs xyz
  fi
  command -v xyz;
}

something like this function, but it would be for unknown executables.

So generically it would look something like:

function on_not_found {
  if ! test -f "$1"; then
     load_libs "$1"
  fi
  command -v "$@";
}
2
  • 1
    bash has command_not_found_handle and zsh command_not_found_handler - some discussion here Command not found message Commented Feb 18, 2022 at 19:47
  • ok cool, is there a way to override that function somehow? seems worthy of an answer not a comment to me Commented Feb 18, 2022 at 20:08

1 Answer 1

2

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)"'
}'
2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .