Is there a bash builtin for 'which'?

Solution 1:

You can use type, which is a Bash builtin:

$ type -P which
which is /usr/bin/which

For documentation, see help [t]ype, which refers to the type section in the bash man page.

(help type prints the help pages for two builtins which start with the string "type", one of which is obsolete and completely unrelated to this.)

Solution 2:

You can use type or command -v. The output of type is human readable; the output of command -v can be executed by Bash.

Note that they are actually a little different. type and command look up the hashed value of the command. That is to say, if you type cmd, type cmd or command -v cmd will tell you exactly what will be run. They also work on aliases, Bash functions, and Bash builtins (although type -p will ignore these and only return true files).

which just does a search on the PATH. This is different because:

  • If there is an alias, function, or builtin with the same name, it will be called instead.
  • If a command was added earlier in the PATH since it was last hashed, it will be found by which, but executing that command will use the hashed value (you can force update the hash in Bash with hash -r).

Usually people really want type, not which, at least for interactive use, as they use it to find out "where is this command coming from when I run it?" You should only use which if you really want to do a PATH lookup.