32

I've read in some bash FAQ a while ago (that I don't remember), that which should be avoided and command -v preferred.

Why is that so? What are the advantages, disadvantages of either one?

Ian Kemp
  • 24,155
  • 16
  • 97
  • 121
adrelanos
  • 1,119
  • 1
  • 13
  • 26
  • 2
    What? Why? `which` tells you where the executable of the program is located while `command -v` usually shows the _version_ of the executable – ForceBru May 05 '16 at 17:02
  • 5
    Here is the link: [Check if a program exists from a Bash script](http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script) – anishsane May 05 '16 at 17:04
  • 3
    @anishsane - this question is "which is better", not "how do I..". While the answer to that other question does explain the difference, the question itself is different. – ghoti May 05 '16 at 17:20
  • 2
    Another builtin you can use in place of which is `type -p`. There is nothing wrong with `which` and it is provided on most distributions by default, but it isn't a shell builtin. – David C. Rankin May 05 '16 at 17:20
  • 1
    Oh, I meant "check the answer to that question". The question starts with _'ve read in some bash FAQ a while ago (that I don't remember)_ So my comment was here is the link. Sorry, I wasn't clear... – anishsane May 06 '16 at 00:49
  • 2
    There are cases where `which` will return a different value from `command -v`, even for binaries. `which` always scans the `$PATH` variable, but bash may hash the command, and not scan for it each time, so it will ignore if it is added/deleted anywhere in those locations. Run `hash` to see which commands have been hashed, or e.g. `type ls` for a specific program – mwfearnley Jun 03 '17 at 13:12

1 Answers1

43

Well...

command is likely built in to your shell, and with the -v option will tell you how your shell will invoke the command specified as its option.

which is an external binary, located at /usr/bin/which which steps through the $PATH environment variable and checks for the existence of a file.

A reason to select the former over the latter is that it avoids a dependency on something that is outside your shell.

The two commands do different things, and you should select the one that more closely matches your needs. For example, if command is built in to your shell, command -v command will indicate this with its output (through the non-existence of path), but which command will try to point to a file on your path, regardless of how command would be interpreted by your shell.

ghoti
  • 41,419
  • 7
  • 55
  • 93