edi9999
edi9999

Reputation: 20554

Is it possible to catch the "command not found" event?

I'm using bash, and wondering if it is possible to catch the "-bash: gitb: command not found" event to replace it with your own handler.

For example, I'd like that if I run

gitb clone instead of git clone, it gets automatically corrected.

It would be possible if I could catch the command not found event, check that the command starts with git and the first word is 4 characters long (or I might enter any kind of rules in a bash script).

It would also make it possible to automagically create aliases to other commands, without having to create those by hand (or with a loop).

Is they such functionality in bash (I'm using version 4.1) ? Any other ideas appreciated !

Upvotes: 1

Views: 345

Answers (1)

chepner
chepner

Reputation: 531265

When a command isn't found, bash will execute the function command_not_found_handle, if defined. As an example:

command_not_found_handle () {
    cmd=$1
    shift
    if [[ ${#cmd} -gt 3 && $cmd = git* ]]; then
        git "$@"
    else
        return 127
    fi
}

Upvotes: 5

Related Questions