4

When I type (in bash) a command which linux does not find, it usually does something like this:

$ x
x: command not found

but when I type a command which is not found but which is similar in some sense to other possible commands, the reply may look like this:

$ pyp
No command 'pyp' found, did you mean:
 Command 'pcp' from package 'pcp' (universe)
 Command 'pype' from package 'pype' (universe)
 Command 'pgp' from package 'pgpgpg' (universe)
 Command 'pp' from package 'libpar-packer-perl' (universe)
 Command 'php' from package 'php5-cli' (main)
 Command 'gyp' from package 'gyp' (universe)
 Command 'pip' from package 'python-pip' (universe)
 Command 'pap' from package 'netatalk' (universe)
pyp: command not found

That means that some hook checked pyp before it let bash reply with pyp: command not found.

I'd like to write a hook like that, that will check if the "command" is a name of a branch in a current repository (if we're indeed in a repository), and will try to checkout into it before replying with command not found, but only if the command was really not found.

To this end, I need to understand something about the flow; when I type the command (and press enter), where does it go to? What is the program which replies with "did you mean", and how does it get the command string from bash?

3

You have to replace / change the command_not_found_handle shell function:

type command_not_found_handle
0

The command-not-found package is responsible for that behavior in Debian and Ubuntu. It's not needed to define your own handler, though. You can use command_not_found_handle as follows:

command_not_found_handle() {
    if [ -d .git ] || git rev-parse --is-git-dir 2>/dev/null; then
        git checkout "$1" 2>/dev/null
    else
        printf '%s: %s: command not found\n' "$0" "$1"
        return 127
    fi
}

To suppress messages like Your branch is up-to-date with 'origin/master'., use &> instead of 2>: git checkout "$1" &>/dev/null.

Example

nyuszika7h@cadoth ~ > master
-bash: master: command not found
127 nyuszika7h@cadoth ~ > cd src/github/nyuszika7h/Limnoria/
nyuszika7h@cadoth ~/src/github/nyuszika7h/Limnoria master > testing
Your branch is up-to-date with 'origin/testing'.
nyuszika7h@cadoth ~/src/github/nyuszika7h/Limnoria testing > foobar
-bash: foobar: command not found
127 nyuszika7h@cadoth ~/src/github/nyuszika7h/Limnoria testing >

Sources

zsh - Check if current directory is a Git repository - Stack Overlow

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.